网络编程
位置:首页>> 网络编程>> Python编程>> Pandas中两个dataframe的交集和差集的示例代码

Pandas中两个dataframe的交集和差集的示例代码

作者:JasonLiu1919  发布时间:2022-05-24 14:52:37 

标签:Pandas,dataframe,交集,差集

创建测试数据:


import pandas as pd
import numpy as np

#Create a DataFrame
df1 = {
 'Subject':['semester1','semester2','semester3','semester4','semester1',
       'semester2','semester3'],
 'Score':[62,47,55,74,31,77,85]}

df2 = {
 'Subject':['semester1','semester2','semester3','semester4'],
 'Score':[90,47,85,74]}

df1 = pd.DataFrame(df1,columns=['Subject','Score'])
df2 = pd.DataFrame(df2,columns=['Subject','Score'])

print(df1)
print(df2)

运行结果:

Pandas中两个dataframe的交集和差集的示例代码

求两个dataframe的交集


intersected_df = pd.merge(df1, df2, how='inner')
print(intersected_df)

Pandas中两个dataframe的交集和差集的示例代码

也可以指定求交集的列:


intersected_df = pd.merge(df1, df2, on=['Subject'], how='inner')
print(intersected_df)

Pandas中两个dataframe的交集和差集的示例代码

求差集

df2-df1:


set_diff_df = pd.concat([df2, df1, df1]).drop_duplicates(keep=False)
print(set_diff_df)

Pandas中两个dataframe的交集和差集的示例代码

df1-df2:


set_diff_df = pd.concat([df1, df2, df2]).drop_duplicates(keep=False)
print(set_diff_df)

Pandas中两个dataframe的交集和差集的示例代码

另一种求差集的方法是:

以df1-df2为例:


df1 = df1.append(df2)
df1 = df1.append(df2)
set_diff_df = df1.drop_duplicates(subset=['Subject', 'Score'],keep=False)
print(set_diff_df)

得到的df1-df2结果是一样的:

Pandas中两个dataframe的交集和差集的示例代码

来源:https://blog.csdn.net/ljp1919/article/details/107165778/

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com