![](/img/trans.png)
[英]Pandas, merging two dataframes on multiple columns, and multiplying result
[英]Merging two pandas dataframes on multiple columns
我有兩個數據框:
>>> df1
[Output]: col1 col2 col3 col4
a abc 10 str1
b abc 20 str2
c def 20 str2
d abc 30 str2
>>> df2
[Output]: col1 col2 col3 col5 col6
d abc 30 str6 47
b abc 20 str5 66
c def 20 str7 53
a abc 10 str5 21
以下是我要生成的內容:
>>> df_merged
[Output]: col1 col2 col5
a abc str5
b abc str5
c def str7
d abc str6
我不想生成超過4行,通常是在嘗試合並數據幀時發生的情況。 感謝您的提示!
df_merged = pd.DataFrame()
df_merged['col1'] = df1['col1'][0:3]
df_merged['col2'] = df1['col2'][0:3]
df_merged['col5'] = df2['col5'][0:3]
這對您要尋找的內容有幫助嗎?
通過子選擇正確的列並使用col1
和col2
作為鍵列來使用.merge
:
df1[['col1', 'col2']].merge(df2[['col1', 'col2', 'col5']], on=['col1', 'col2'])
col1 col2 col5
0 a abc str5
1 b abc str5
2 c def str7
3 d abc str6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.