![](/img/trans.png)
[英]Python pandas find element of one column in list of elements of another column
[英]Is there a way to do a merge using pandas where one column is a list and another column might contain an element in that list?
现在我有两个pandas数据帧:
第一个看起来像这样:
id1 features
0 ['a', 'b']
1 ['c', 'd', 'e']
2 ['f']
第二个看起来像这样:
id2 features other
224 'a' 3
264 'z' 3
277 'f' 3
我想使用pandas .merge()
函数来结合两者。 输出应该如下所示:
id1 features other
0 'a' 3
2 'f' 3
我知道可能有一种方法可以通过将第一个数据帧扩展为每个值的多行然后进行连接来实现,但我想知道是否有任何方法可以在不执行此操作的情况下执行此操作,或者最简洁的方法是是。
我认为你实际上描述了最有效的方法: expanding the first dataframe into multiple rows per value then doing the join
。
我能看到的另一个选择是迭代第二个选项。 说
df1 =\
id features
0 ['a', 'b']
1 ['c', 'd', 'e']
2 ['f']
df2 =\
id features other
0 'a' 3
1 'z' 3
2 'f' 3
做类似的事情:
features_in_df1 = set(np.flatten(df1.feature.values))
output = []
for _, row in df2.iterrows():
if row['feature'] in features_in_df1:
output.append(row)
df_merge = pd.concat(output)
IIUC
s=df1.merge(df2,on='id')
df2[[y in x for x , y in zip(s.features_x,s.features_y)]]
id features other
0 0 a 3
2 2 f 3
更新
df2[df2.features.isin(df1.features.sum())]
id features other
0 0 a 3
2 2 f 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.