欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解利用Pandas求解兩個(gè)DataFrame的差集,交集,并集

 更新時(shí)間:2022年07月15日 08:34:07   作者:尤而小屋  
這篇文章主要和大家講解一下如何利用Pandas函數(shù)求解兩個(gè)DataFrame的差集、交集、并集,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下

大家好,我是Peter~

本文講解的是如何利用Pandas函數(shù)求解兩個(gè)DataFrame的差集、交集、并集。

模擬數(shù)據(jù)

模擬一份簡(jiǎn)單的數(shù)據(jù):

In [1]:

import?pandas?as?pd

In [2]:

df1?=?pd.DataFrame({"col1":[1,2,3,4,5],
????????????????????"col2":[6,7,8,9,10]
???????????????????})

df2?=?pd.DataFrame({"col1":[1,3,7],
????????????????????"col2":[6,8,10]
???????????????????})

In [3]:

df1

Out[3]:

 col1col2
016
127
238
349
4510

In [4]:

df2

Out[4]:

 col1col2
016
138
2710

兩個(gè)DataFrame的相同部分:

差集

方法1:concat + drop_duplicates

In [5]:

df3?=?pd.concat([df1,df2])
df3

Out[5]:

 col1col2
016
127
238
349
4510
016
138
2710

In [6]:

#?結(jié)果1

df3.drop_duplicates(["col1","col2"],keep=False)

Out[6]:

 col1col2
127
349
4510
2710

方法2:append + drop_duplicates

In [7]:

df4?=?df1.append(df2)
df4

Out[7]:

 col1col2
016
127
238
349
4510
016
138
2710

In [8]:

#?結(jié)果2

df4.drop_duplicates(["col1","col2"],keep=False)

Out[8]:

 col1col2
127
349
4510
2710

交集

方法1:merge

In [9]:

#?結(jié)果

#?等效:df5 = pd.merge(df1, df2, how="inner")
df5?=?pd.merge(df1,df2)

df5

Out[9]:

 col1col2
016
138

方法2:concat + duplicated + loc

In [10]:

df6?=?pd.concat([df1,df2])
df6

Out[10]:

 col1col2
016
127
238
349
4510
016
138
2710

In [11]:

s?=?df6.duplicated(subset=['col1','col2'],?keep='first')
s

Out[11]:

0    False
1    False
2    False
3    False
4    False
0     True
1     True
2    False
dtype: bool

In [12]:

#?結(jié)果
df8?=?df6.loc[s?==?True]
df8

Out[12]:

 col1col2
016
138

方法3:concat + groupby + query

In [13]:

#?df6?=?pd.concat([df1,df2])

df6

Out[13]:

 col1col2
016
127
238
349
4510
016
138
2710

In [14]:

df9?=?df6.groupby(["col1",?"col2"]).size().reset_index()
df9.columns?=?["col1",?"col2",?"count"]

df9

Out[14]:

 col1col2count
0162
1271
2382
3491
45101
57101

In [15]:

df10?=?df9.query("count?>?1")[["col1",?"col2"]]
df10

Out[15]:

 col1col2
016
238

并集

方法1:concat + drop_duplicates

In [16]:

df11?=?pd.concat([df1,df2])
df11

Out[16]:

 col1col2
016
127
238
349
4510
016
138
2710

In [17]:

#?結(jié)果

#?df12?=?df11.drop_duplicates(subset=["col1","col2"],keep="last")
df12?=?df11.drop_duplicates(subset=["col1","col2"],keep="first")
df12

Out[17]:

 col1col2
016
127
238
349
4510
2710

方法2:append + drop_duplicates

In [18]:

df13?=?df1.append(df2)

#?df13.drop_duplicates(subset=["col1","col2"],keep="last")
df13.drop_duplicates(subset=["col1","col2"],keep="first")

Out[18]:

 col1col2
016
127
238
349
4510
2710

方法3:merge

In [19]:

pd.merge(df1,df2,how="outer")

Out[19]:

 col1col2
016
127
238
349
4510
5710

以上就是詳解利用Pandas求解兩個(gè)DataFrame的差集,交集,并集的詳細(xì)內(nèi)容,更多關(guān)于Pandas DataFrame差集 交集 并集的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論