根据另一个数据框

时间:2018-06-02 09:21:20

标签: python pandas filter merge

我有2个数据帧

df1

Company           SKU   Sales
Walmart           A     100
Total             A     200
Walmart           B     200
Total             B     300
Walmart           C     400
Walmart           D     500

DF2

 Company             SKU   Sales
 Walmart             A     400
 Total               B     300
 Walmart             C     900
 Walmart             F     400
 Total               G     500

我想要一个结果数据帧(df2),它只有df1和df2中匹配SKU的记录

DF2

Company       SKU   Sales 
Walmart       A     400
Total         B     300
Walmart       C     900

我只想在df2

中使用df1的唯一(公司+ SKU)值

有没有很好的解决方案来实现这个目标?

3 个答案:

答案 0 :(得分:2)

<强>更新

您可以使用简单的面具:

m = df2.SKU.isin(df1.SKU)
df2 = df2[m]

您正在寻找内部联接。试试这个:

df3 = df1.merge(df2, on=['SKU','Sales'], how='inner')

#  SKU  Sales
#0   A    100
#1   B    200
#2   C    300

或者这个:

df3 = df1.merge(df2, on='SKU', how='inner')

#  SKU  Sales_x  Sales_y
#0   A      100      100
#1   B      200      200
#2   C      300      300

答案 1 :(得分:2)

解决方案1:

# First identify the common SKU's    
temp = list(set(list(df1.SKU)).intersection(set(list(df2.SKU))))

# Filter df2 using the list of common SKU's
df3 = df2[df2.SKU.isin(temp)]
print(df3)

   SKU  Sales
0   A   400
1   B   300
2   C   900

解决方案2:One Line解决方案

df3 = df2[df2.SKU.isin(list(df1.SKU))]

编辑1:更新问题的解决方案(不是最佳方式,但回答你的问题)

# reading data for df1
df1= pd.read_clipboard(sep='\\s+')
df1
    Company SKU Sales
0   Walmart A   100
1   Total   A   200
2   Walmart B   200
3   Total   B   300
4   Walmart C   400
5   Walmart D   500

# reading data for df2
df2= pd.read_clipboard(sep='\\s+')
df2
Company SKU Sales
0   Walmart A   400
1   Total   B   300
2   Walmart C   900
3   Walmart F   400
4   Total   G   500

# Using intersect and zip to create a list of tuples matching in the data frames
temp = list(set(list(zip(df1.Company,df1.SKU))).intersection(set(list(zip(df2.Company,df2.SKU)))))
temp
[('Walmart', 'A'), ('Walmart', 'C'), ('Total', 'B')]

# Creating a helper variable in df2 to lookup in the temp list
df2["temp"] = list(zip(df2.Company,df2.SKU))
df2= df2[df2["temp"].isin(temp)]
del(df2["temp"])
df2
    Company SKU Sales
0   Walmart A   400
1   Total   B   300
2   Walmart C   900

欢迎建议改进此代码

答案 2 :(得分:1)

一种方法是对齐索引然后使用掩码。

# align indices
df1 = df1.set_index(['Company',  'SKU'])
df2 = df2.set_index(['Company',  'SKU'])

# calculate & apply mask
df2 = df2[df2.index.isin(df1.index)].reset_index()

不需要重置索引,但需要将CompanySKU提升为列。