简体   繁体   中英

How to update a dataframe with values from another dataframe when indexes and columns don't not match

I want to update the dataframe df with the values coming from another dataframe df_new if some condition hold true.

The indexes and the columns names of the dataframes does not match. How could it be done?

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

One idea with Series.reindex for match index values of mask with another DataFrame:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM