[英]Python Dataframe: Assign Values to a column based on other column?
我有 df 三列a
, b
, c
。我想更改b
列中的NaN
值。 例如:对于a
列中的123
的值, b
列同时具有abc
和NaN
。 我希望两者都更改为abc
。
raw_data = {'a': [123, 123, 456, 456],
'b': [np.nan,'abc','def',np.nan],
'c':[np.nan,np.nan,0,np.nan]}
df = pd.DataFrame(raw_data, columns = ['a', 'b','c'])
a b c
0 123 NaN NaN
1 123 abc NaN
2 456 def 0
3 456 NaN NaN
我的预期 Output
df
a b c
1 123 abc NaN
0 123 abc NaN
2 456 def 0
3 456 def NaN
我试过的:
df = df.sort_values(by=['a','b']).fillna(method='ffill')
但这也改变了column c
。
Output 从上面:
a b c
1 123 abc NaN
0 123 abc NaN
2 456 def 0
3 456 def 0
我如何将ffill
用于特定列或推荐的任何其他方法?
样本数据 2:
raw_data = {'a': [123, 123, 456, 456,789,np.nan],
'b': [np.nan,'abc','def',np.nan,np.nan,'ghi'],
'c':[np.nan,np.nan,0,np.nan,np.nan,np.nan]}
df = pd.DataFrame(raw_data, columns = ['a', 'b','c'])
a b c
0 123.0 NaN NaN
1 123.0 abc NaN
2 456.0 def 0
3 456.0 NaN NaN
4 789.0 NaN NaN
5 NaN ghi abc
预计 Output
a b c
0 123.0 abc NaN
1 123.0 abc NaN
2 456.0 def 0
3 456.0 def NaN
4 789.0 NaN NaN
5 NaN ghi abc
对于您的新更新数据,您应该使用Series.map
:
df['b'] = df['a'].map(df.groupby('a')['b'].first()).fillna(df['b'])
a b c
0 123.0 abc NaN
1 123.0 abc NaN
2 456.0 def 0.0
3 456.0 def NaN
4 789.0 NaN NaN
5 NaN ghi NaN
旧答案
将groupby
与ffill
和bfill
使用:
df['b'] = df.groupby('a')['b'].ffill().bfill()
a b c
0 123 abc NaN
1 123 abc NaN
2 456 def 0.0
3 456 def NaN
fillna
function 适用于所有DataFrame
。 一种解决方案是截断您的DataFrame
以便仅包含您要修改的列,并仅对其应用fillna
,然后添加回另一列:
df_ab = df.loc[:,["a","b"]]
df_ab = df_ab.sort_values(by=['a','b']).fillna(method='ffill')
df_ab["c"] = df["c"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.