2 回答

TA贡献1862条经验 获得超7个赞
嗯,这很有效……不确定它是有史以来最pythonic的解决方案,但它是这样的:
df.loc[df['foo'] == 1, 'Output Column'] = df.loc[df['bar'] == 2, 'Desired Column'] df['Output Column'] = df.groupby(['foo'])['Output Column'].transform(max)
在我的玩具示例中,这填充了对应于 bar=2 的单个数字

TA贡献1811条经验 获得超4个赞
尝试使用where:
df['Output Column']=df['Output Column'].where(df['bar']==2,'Hi There!')
print(df)
输出:
idx foo bar Desired Column Output Column
0 0 1 NaN NaN Hi there!
1 1 NaN 2 Hi there! NaN
要将 NaN 替换为'',请执行以下操作:
df=df.fillna('')
之后where。
然后:
print(df)
将:
idx foo bar Desired Column Output Column
0 0 1 Hi there!
1 1 2 Hi there!
或者更不用手动操作,请执行以下操作:
df['Output Column']=df['Output Column'].where(df['bar']==2,df.loc[df['bar']==2,'Desired Column'].tolist())
print(df)
然后可以做同样的事情来替换 NaN ''
更新:
第一的:
df['Output Column']=df['Output Column'].where(df['foo']!=1,'Hi There!')
print(df)
输出:
Desired Column Output Column bar foo idx
0 NaN Hi There! NaN 1.0 0
1 Hi There! NaN 2.0 NaN 1
2 NaN Hi There! NaN 1.0 2
3 NaN NaN NaN 6.0 3
第二:
df['Output Column']=df['Output Column'].where(df['foo'].notnull(),'Hi There!')
print(df)
输出:
Desired Column Output Column bar foo idx
0 NaN NaN NaN 1.0 0
1 Hi There! Hi There! 2.0 NaN 1
2 NaN NaN NaN 1.0 2
3 NaN NaN NaN 6.0 3
可以做同样的事情来替换 NaN ''
添加回答
举报