免责声明:这可能是重复的,但我找不到确切的解决方案。请随意将此问题标记为重复,并在评论中提供重复问题的链接。
我仍在学习 python 数据帧操作,这可能有一个非常简单的解决方案,我无法弄清楚。
我有一个带有单列的 python 数据框。现在,如果满足某些条件,我想将每行的值更改为前一行的值。我创建了一个循环解决方案来实现此目的,但我希望有一个更有效的解决方案。
初始数据的创建:
import numpy as np
import pandas as pd
data = np.random.randint(5,30,size=20)
df = pd.DataFrame(data, columns=['random_numbers'])
print(df)
random_numbers
0 6
1 24
2 29
3 18
4 22
5 17
6 12
7 7
8 6
9 27
10 29
11 13
12 23
13 6
14 25
15 24
16 16
17 15
18 25
19 19
现在假设两个条件是 1) 值小于 10 和 2) 值大于 20。在任何这些情况下,将行值设置为前一行值。这已以循环格式实现,如下所示:
for index,row in df.iterrows():
if index == 0:
continue;
if(row.random_numbers<10):
df.loc[index,'random_numbers']=df.loc[index-1,'random_numbers']
if(row.random_numbers>20):
df.loc[index,'random_numbers']=df.loc[index-1,'random_numbers']
random_numbers
0 6
1 6
2 6
3 18
4 18
5 17
6 12
7 12
8 12
9 12
10 12
11 13
12 13
13 13
14 13
15 13
16 16
17 15
18 15
19 19
由于我使用大量行,请建议一种更有效的方法来实现此逻辑。