df1
看起来像这样:
attribute_1 attribute_2
0 A Y
1 A Z
2 B Y
3 B Z
df1 = pd.DataFrame({'attribute_1': ['A', 'A', 'B', 'B'],
'attribute_2': ['Y', 'Z', 'Y', 'Z']})
df2
更大,具有相同属性值的多行,也有许多与df1
不同的列:
attribute_1 attribute_2 fruit
0 A Y apple
1 A Y banana
2 A Z melon
3 B Z orange
4 B Z grape
5 B Y pear
6 B Z orange
df2 = pd.DataFrame({'attribute_1': ['A', 'A', 'A', 'B', 'B', 'B', 'B'],
'attribute_2': ['Y', 'Y', 'Z', 'Z', 'Z', 'Y', 'Z'],
'fruit': ['apple', 'banana', 'melon', 'orange', 'grape', 'pear', 'orange']})
我想在df1
中添加一列,以检查相应属性df2.fruit
是否有任何值在['apple', 'orange']
中,以创建desired_df
:
attribute_1 attribute_2 has_apple_or_orange
0 A Y True
1 A Z False
2 B Y False
3 B Z True
desired_df = pd.DataFrame({'attribute_1': ['A', 'A', 'B', 'B'],
'attribute_2': ['Y', 'Z', 'Y', 'Z'],
'has_apple_or_orange': [True, False, False, True]})
我该怎么做?以某种方式合并?
不确定如何描述这一点,所以如果这已经在其他地方回答了,请原谅我。
首先将值按Series.isin
与具有DataFrame.assign
的新列进行比较,然后按GroupBy.any
聚合并将新列添加到第二列DataFrame
DataFrame.join
:
f = ['apple', 'orange']
s = (df2.assign(has_apple_or_orange = df2['fruit'].isin(f))
.groupby(['attribute_1','attribute_2'])['has_apple_or_orange']
.any())
print (s)
attribute_1 attribute_2
A Y True
Z False
B Y False
Z True
Name: has_apple_or_orange, dtype: bool
df = df1.join(s, on=['attribute_1','attribute_2'])
print (df)
attribute_1 attribute_2 has_apple_or_orange
0 A Y True
1 A Z False
2 B Y False
3 B Z True
一种可能的解决方案:
index = ["attribute_1","attribute_2"]
(df1.set_index(index).join(df2.set_index(index))
.fruit.isin(["apple","orange"])
.reset_index()
.drop_duplicates(index)
)
attribute_1 attribute_2 fruit
0 A Y True
2 A Z False
3 B Y False
4 B Z True
不过,@jezrael的解决方案似乎更强大,因为它考虑了分组