首页 > 解决方案 > 当索引和列不匹配时,如何使用来自另一个数据帧的值更新数据帧

问题描述

如果某些条件成立,我想df用来自另一个数据帧的值更新数据帧。df_new

数据框的索引和列名不匹配。怎么可能做到?

names = ['a', 'b', 'c']
df = pd.DataFrame({
    'val': [10, 10, 10],
}, index=names)

new_names = ['a', 'c', 'd']
df_new = pd.DataFrame({
    'profile': [5, 15, 22],
}, index=new_names)

above_max = df_new['profile'] >= 7

# This works only if indexes of df and df_new match
#df.loc[above_max, 'val'] = df_new['profile']

#  expected df:
#    val
# a   10
# b   10
# c   15

标签: pythonpandasdataframe

解决方案


Series.reindex将掩码的索引值与另一个 DataFrame 匹配的一个想法:

s = df_new['profile'].reindex(df.index)
above_max = s >= 7
df.loc[above_max, 'val'] = s

推荐阅读