簡體   English   中英

Pandas,如何將系列添加到 DataFrame 列,其中系列索引與 DataFrame 列匹配?

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

我有一個 Pandas DataFrame 和一個系列。 他們的一個樣本是:

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)

如何將series的值添加到df中的value列,其中series的索引與dfkey列匹配? 注意不是seriesd不會改變。 對於上面的例子,我想以:

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

您可以簡單地使用a作為查找字典:

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

你關心指數嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM