简体   繁体   English

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

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

I have a pandas DataFrame, and a Series.我有一个 Pandas DataFrame 和一个系列。 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 ?如何将series的值添加到df中的value列,其中series的索引与dfkey列匹配? Note key d which isn't in series does not change.注意不是seriesd不会改变。 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:您可以简单地使用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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 熊猫向数据框列添加系列 - Pandas add a series to dataframe column 如何将Series添加为DataFrame(Pandas)中的列? - How to add Series as a column in a DataFrame (Pandas)? 从系列或字典向数据帧添加一个新列,将我的系列索引和数据帧列映射到键熊猫 python - Add a new column to a dataframe from a Series or dictionary mapping my series index and a dataframe column to key pandas python Pandas:将系列添加到数据框作为列(相同的索引,不同的长度) - Pandas: Add series to dataframe as a column (same index, different length) 将pandas Series作为列添加到多索引的DataFrame填充级别 - Add pandas Series as a column to DataFrame filling levels of multi-index Pandas 系列索引作为数据框的列名 - Pandas series index as column name of dataframe Pandas - 根据与数据框中某个值匹配的系列索引,将系列中的值添加到数据框列 - Pandas - Add values from series to dataframe column based on index of series matching some value in dataframe 熊猫:将系列添加到按列排序的DataFrame中 - Pandas: Add Series to DataFrame ordered by column pandas 在时间序列上将列添加到 dataframe 聚合 - pandas add column to dataframe aggregate on time series How do I turn a Pandas DataFrame object with 1 main column into a Pandas Series with the index column from the original DataFrame - How do I turn a Pandas DataFrame object with 1 main column into a Pandas Series with the index column from the original DataFrame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM