[英]Find common values between 3 DataFrames?
我有3個數據框:df1,df2和df3。
df1 = 'num' 'type'
23 a
34 b
89 a
90 c
df2 = 'num' 'type'
23 a
34 b
56 a
90 c
df3 = 'num' 'type'
56 a
34 s
71 a
90 c
我想要的是出現在2個或多個dfs中的所有'num'值的輸出,並且我想標記該'num'值出現在多少個dfs中。所以我想要這樣的東西:
df = 'num' 'type' 'count'
23 a 2
34 s 3
90 c 3
56 a 2
我嘗試進行內部合並,但這僅考慮了在所有3個df中出現的“ num”值,而忽略了在2/3 dfs中出現的值。 最好的方法是什么?
等我的朋友
df_full = pd.concat([df1,df2,df3], axis = 0)
df_agg = df_full.groupby('num').agg({'type': 'count'})
df_agg = df_agg.loc[df_agg['type'] >= 2]
這是collections.Counter
解決方案,具有O(n)復雜度。
如果需要,計數結果可以很容易地帶回pandas
。
from collections import Counter
c = sum((Counter(df['num']) for df in [df1, df2, df3]), Counter())
c_masked = {k: v for k, v in c.items() if v>=2}
# {23: 2, 34: 3, 90: 3, 56: 2}
df = pd.DataFrame.from_dict(c_masked, orient='index')
# 0
# 23 2
# 34 3
# 90 3
# 56 2
這是使用groupby和size獲得所需結果的另一種方法
d1 = {'num': [23,34,89,90], 'type': ['a', 'b', 'a', 'c']}
d2 = {'num': [23,34,56,90], 'type': ['a', 'b', 'a', 'c']}
d3 = {'num': [56,34,71,90], 'type': ['a', 's', 'a', 'c']}
df1 = pd.DataFrame(data=d1)
df2 = pd.DataFrame(data=d2)
df3 = pd.DataFrame(data=d3)
df10 = pd.concat([df1,df2,df3], axis=0)
# Using groupby with 'num' and 'type' and then using size to get the count.
# resent_index(name='count') will name the size column as 'count'
df20 = df10.groupby(['num','type']).size().reset_index(name='count')
# getting the index with 'count' >= 2 and storing those in df_out.
df_out = df20[df20['count'] >=2].reset_index(drop=True)
print(df_out)
輸出如下:
num type count
0 23 a 2
1 34 b 2
2 56 a 2
3 90 c 3
以供參考
print(df20)
num type count
0 23 a 2
1 34 b 2
2 34 s 1
3 56 a 2
4 71 a 1
5 89 a 1
6 90 c 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.