Python 在应用函数中执行移位
我试图用另一列和上面一行的值填充一些NaN值 例如,我得到的数据帧如下所示:Python 在应用函数中执行移位,python,pandas,Python,Pandas,我试图用另一列和上面一行的值填充一些NaN值 例如,我得到的数据帧如下所示: Distance Down firstDownYards secondDownYards 1 10.0 1.0 NaN NaN 2 8.0 2.0 2.0 NaN 3 8.0 3.0 2.0 0.0 4
Distance Down firstDownYards secondDownYards
1 10.0 1.0 NaN NaN
2 8.0 2.0 2.0 NaN
3 8.0 3.0 2.0 0.0
4 19.0 3.0 -9.0 -11.0
5 19.0 4.0 -9.0 -11.0
6 10.0 1.0 NaN NaN
7 5.0 2.0 5.0 NaN
8 5.0 3.0 5.0 0.0
9 10.0 1.0 NaN NaN
10 9.0 2.0 1.0 NaN
11 11.0 3.0 -1.0 -2.0
12 12.0 4.0 -2.0 -3.0
13 10.0 1.0 NaN NaN
14 5.0 2.0 5.0 NaN
15 10.0 1.0 NaN NaN
16 8.0 2.0 2.0 NaN
17 8.0 3.0 2.0 0.0
18 10.0 1.0 NaN NaN
19 10.0 2.0 0.0 NaN
20 6.0 3.0 4.0 4.0
在第二个下行区,我想用下一排列第一个下行区的对面填充下行区低于2的NaN。下面是该列的示例:
Distance Down firstDownYards secondDownYards
1 10.0 1.0 NaN -2 # Change here
2 8.0 2.0 2.0 NaN
3 8.0 3.0 2.0 0.0
4 19.0 3.0 -9.0 -11.0
5 19.0 4.0 -9.0 -11.0
6 10.0 1.0 NaN -5 # Change here
7 5.0 2.0 5.0 NaN
8 5.0 3.0 5.0 0.0
9 10.0 1.0 NaN -1 # Change here
10 9.0 2.0 1.0 NaN
11 11.0 3.0 -1.0 -2.0
12 12.0 4.0 -2.0 -3.0
13 10.0 1.0 NaN -5 # Change here
14 5.0 2.0 5.0 NaN
15 10.0 1.0 NaN -2 # Change here
16 8.0 2.0 2.0 NaN
17 8.0 3.0 2.0 0.0
18 10.0 1.0 NaN 0 # Change here
19 10.0 2.0 0.0 NaN
20 6.0 3.0 4.0 4.0
我曾尝试创建一个类似这样的函数,但当我尝试打印x.shift()时,它只打印与x相同的内容。然后我将使用df.apply(getLastCol,args=(..),axis=1)。
downNb是条件,在本例中为2。
currentCol和lastCol是当前列和上一列的名称
def getLastCol(x,downNb,currentCol,lastCol):
if x['Down'] < downNb:
print(x.shift())
value = x.shift(-1)[lastCol]
else:
value = x[currentCol]
return value
def getLastCol(x,downNb,currentCol,lastCol):
如果x['Down']
使用shift
和loc
到位
您还提到了secondDownYards
也必须是NaN
的条件。在您的示例中,情况总是这样,如果不保证,并且您只希望替换NaN
值,您还可以添加该检查:
df.loc[df.Down.lt(2) & df.secondDownYards.isnull(), 'secondDownYards'] # ...
使用
np.where
和assign
此选项的优点是不就地修改数据帧:
df.assign(
secondDownYards= np.where(
df.Down.lt(2), df.firstDownYards.shift(-1).mul(-1), df.secondDownYards
))
这两个选项都会产生所需的输出:
Distance Down firstDownYards secondDownYards
1 10.0 1.0 NaN -2.0
2 8.0 2.0 2.0 NaN
3 8.0 3.0 2.0 0.0
4 19.0 3.0 -9.0 -11.0
5 19.0 4.0 -9.0 -11.0
6 10.0 1.0 NaN -5.0
7 5.0 2.0 5.0 NaN
8 5.0 3.0 5.0 0.0
9 10.0 1.0 NaN -1.0
10 9.0 2.0 1.0 NaN
11 11.0 3.0 -1.0 -2.0
12 12.0 4.0 -2.0 -3.0
13 10.0 1.0 NaN -5.0
14 5.0 2.0 5.0 NaN
15 10.0 1.0 NaN -2.0
16 8.0 2.0 2.0 NaN
17 8.0 3.0 2.0 0.0
18 10.0 1.0 NaN -0.0
19 10.0 2.0 0.0 NaN
20 6.0 3.0 4.0 4.0
Distance Down firstDownYards secondDownYards
1 10.0 1.0 NaN -2.0
2 8.0 2.0 2.0 NaN
3 8.0 3.0 2.0 0.0
4 19.0 3.0 -9.0 -11.0
5 19.0 4.0 -9.0 -11.0
6 10.0 1.0 NaN -5.0
7 5.0 2.0 5.0 NaN
8 5.0 3.0 5.0 0.0
9 10.0 1.0 NaN -1.0
10 9.0 2.0 1.0 NaN
11 11.0 3.0 -1.0 -2.0
12 12.0 4.0 -2.0 -3.0
13 10.0 1.0 NaN -5.0
14 5.0 2.0 5.0 NaN
15 10.0 1.0 NaN -2.0
16 8.0 2.0 2.0 NaN
17 8.0 3.0 2.0 0.0
18 10.0 1.0 NaN -0.0
19 10.0 2.0 0.0 NaN
20 6.0 3.0 4.0 4.0