简体   繁体   中英

Pandas, how to add Series to DataFrame column, where series index matches a DataFrame column?

I have a pandas DataFrame, and a Series. They a sample is:

b = [
        {'key': 'c', 'value': 10},
        {'key': 'a', 'value': 5},
        {'key': 'b', 'value': 3},
        {'key': 'd', 'value': 99}
]
df = pd.DataFrame(b)
a = {'a': 1, 'b': 2, 'c': 3} 
series = pd.Series(a)

How can I add the values of series , to the value column in df where the index of series matches the key column of df ? Note key d which isn't in series does not change. For the example above, I want to end up with:

result_data = [
        {'key': 'c', 'value': 13},
        {'key': 'a', 'value': 6},
        {'key': 'b', 'value': 5},
        {'key': 'd', 'value': 99}
]
result_df = pd.DataFrame(result_data)

You can simply use the a as lookup dict:

df['sum'] = df.apply(lambda x: x['value'] + a.get(x['key'], 0), axis=1)

print(df[['key', 'sum']])

  key  sum
0   c   13
1   a    6
2   b    5
3   d   99

do you care about the index?

df = df.set_index('key')
df.add(series, axis=0).fillna(df)

   value
a    6.0
b    5.0
c   13.0
d   99.0

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