基于另一个数据帧的索引更新列值



我有以下数据帧:

NUMS = ['1', '2', '3', '4', '5']
LETTERS = ['a', 'b', 'c']
df1 = pd.DataFrame(index=NUMS, columns=LETTERS)
a    b    c
1  NaN  NaN  NaN
2  NaN  NaN  NaN
3  NaN  NaN  NaN
4  NaN  NaN  NaN
5  NaN  NaN  NaN
df2 = pd.DataFrame([['tom', 10], ['nick', 15], ['james', 14]],
index=LETTERS,
columns=['col', 'col2'])
col  col2
a    tom    10
b   nick    15
c  james    14

我试图用df2更新df1,以便如果该列与df2的索引匹配,则所有行都用col2更新:

a    b    c
1   10   15  14
2   10   15  14
3   10   15  14
4   10   15  14
5   10   15  14

我试过df1.update(df2['col2']),但df1没有更新。

我也尝试过df1.apply(lambda x: df2['col2'].loc[x]),但我得到以下错误:

KeyError: "None of [Float64Index([nan, nan, nan, nan, nan], dtype='float64')] are in the [index]"

谢谢!

try this:

df1.fillna(df2.col2)
>>>
a   b   c
1   10  15  14
2   10  15  14
3   10  15  14
4   10  15  14
5   10  15  14

试试这个:

for column in df1.columns:
df1.loc[:, column] = df2.at[column, 'col2']

最新更新