【问题标题】:How to update a dataframe with values from another dataframe when indexes and columns don't not match当索引和列不匹配时,如何使用来自另一个数据帧的值更新数据帧
【发布时间】:2020-12-01 22:00:14
【问题描述】:

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

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

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

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-19
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 2016-12-20
      • 2015-12-31
      • 1970-01-01
      • 2015-10-19
      相关资源
      最近更新 更多