Mel*_*123 3 python dataframe pandas
您好,我正在尝试使用 .update() 函数使用同一数据框中另一列 (C) 的值更新一列 (B) 的值。但是,我只想替换 B 列中 NaN 的值。我尝试使用 overwrite = False 参数,但我不断收到错误:
df = pd.DataFrame({'A': [1, 2, 3],
'B': [400, np.nan, 600],
'C': [32,54,300]})
df['B'].update(df['C'], overwrite = False)
df
#Output:
#TypeError: update() got an unexpected keyword argument 'overwrite'
#The intended output I'm looking for is this:
A B C
0 1 400.0 32
1 2 54.0 54
2 3 600.0 300
Run Code Online (Sandbox Code Playgroud)
但是,当我使用 update.() 函数更新整个数据集时,覆盖参数有效:
df = pd.DataFrame({'A': [1, 2, 3],
'B': [400, np.nan, 600],
'C': [32,54,300]})
new_df = pd.DataFrame({'B': [4, 5, 6],
'C': [7, 8, 9]})
df.update(new_df, overwrite = False)
df
#Output:
A B C
0 1 400.0 32
1 2 5.0 54
2 3 600.0 300
Run Code Online (Sandbox Code Playgroud)
当用同一数据帧中的另一列更新一列时,覆盖参数是否不起作用?想检查一下如何用另一列的值更新一列,但仅覆盖 NaN 值。太感谢了!
回答你的问题,这一点非常重要。pd.DataFrame.update不等于pd.Series.update. pd.Series.update 中没有overwrite参数。您必须知道您正在使用的对象类型。
让我们使用fillna:
df['B'] = df['B'].fillna(df['C'])
Run Code Online (Sandbox Code Playgroud)
输出:
A B C
0 1 400.0 32
1 2 54.0 54
2 3 600.0 300
Run Code Online (Sandbox Code Playgroud)
或者掩码,或者在哪里,或者其他一些方式......combine_first。