問題描述
我有兩個不同長度的數(shù)據(jù)框:
I have two dataframes of different length like those:
數(shù)據(jù)幀 A:
FirstName LastName
Adam Smith
John Johnson
數(shù)據(jù)幀 B:
First Last Value
Adam Smith 1.2
Adam Smith 1.5
Adam Smith 3.0
John Johnson 2.5
想象一下,我想做的是在DataFrame A"中創(chuàng)建一個新列,將所有具有匹配姓氏的值相加,因此A"中的輸出將是:
Imagine that what I want to do is to create a new column in "DataFrame A" summing all the values with matching last names, so the output in "A" would be:
FirstName LastName Sums
Adam Smith 5.7
John Johnson 2.5
如果我在 Excel 中,我會使用
If I were in Excel, I'd use
=SUMIF(dfB!B:B, B2, dfB!C:C)
在 Python 中,我一直在嘗試多種解決方案,但同時使用 np.where、df.sum()、刪除索引等,但我迷路了.下面的代碼返回ValueError:只能比較標(biāo)記相同的系列對象",但我認為它無論如何都寫不正確.
In Python I've been trying multiple solutions but using both np.where, df.sum(), dropping indexes etc., but I'm lost. Below code is returning "ValueError: Can only compare identically-labeled Series objects", but I don't think it's written correctly anyways.
df_a['Sums'] = df_a[df_a['LastName'] == df_b['Last']].sum()['Value']
非常感謝您的任何幫助.
Huge thanks in advance for any help.
推薦答案
使用 布爾索引
與 Series.isin
進行過濾然后聚合sum
:
df = (df_b[df_b['Last'].isin(df_a['LastName'])]
.groupby(['First','Last'], as_index=False)['Value']
.sum())
如果想同時匹配名字和姓氏:
If want match both, first and last name:
df = (df_b.merge(df_a, left_on=['First','Last'], right_on=['FirstName','LastName'])
.groupby(['First','Last'], as_index=False)['Value']
.sum())
這篇關(guān)于Python:如果DataFrames之間的其他值匹配,則對DataFrame中的值求和的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!