我正在尝试执行以下操作:当“content”的值为NaN时,用目标行的值替换它的值。下面是我的代码,它通过遍历所有行来实现这一点,但它既丑陋又缓慢。我想应该有一个更优雅/快速的方法来做这个面具,所以我想有人可能会在这方面启发我:
Inputs:
import pandas as pd
d = {'content': [1, 3, None, 6, 1, 59, None], 'target': [0,1,0,2,4,5,4]}
df = pd.DataFrame(data=d)
print(df)
for index, row in df.iterrows():
if df.loc[index,'content']!=df.loc[index,'content']: # To detect NaN
df.loc[index,'content']=df.loc[df.loc[index,'target'],'content']
print(df)
outputs:
content target
0 1.0 0
1 3.0 1
2 NaN 0
3 6.0 2
4 1.0 4
5 59.0 5
6 NaN 4
content target
0 1.0 0
1 3.0 1
2 1.0 0
3 6.0 2
4 1.0 4
5 59.0 5
6 1.0 4
提前谢谢!在
注意:只有当该行的内容为“NaN”时,才需要将该行的内容更改为目标行的内容。在
另外一个问题:当内容是59或6时,我能做同样的事情吗?谢谢!在
通过使用
fillna
编辑
^{pr2}$我想你需要这个
分配回来后
让我再编辑一次
相关问题 更多 >
编程相关推荐