Python 通过搜索相邻列来选择一列的内容
我有两个不同的熊猫数据帧集。其中之一是术语列表;这些术语是字符串:Python 通过搜索相邻列来选择一列的内容,python,pandas,dataframe,Python,Pandas,Dataframe,我有两个不同的熊猫数据帧集。其中之一是术语列表;这些术语是字符串: df_1 apple panda lecture sky green 另一个包含两列,其中一列是包含程序标题的字符串,而第二列包含该程序的标记列表 df_2 Program Tags Fruits of the World [what,apple,green,banana,kiwi] Animal in the Zoo
df_1
apple
panda
lecture
sky
green
另一个包含两列,其中一列是包含程序标题的字符串,而第二列包含该程序的标记列表
df_2
Program Tags
Fruits of the World [what,apple,green,banana,kiwi]
Animal in the Zoo [panda,lion,eagle]
Lecture 1 [panda,lecture,red]
The Old Man and the Sea [book, blue, sea, lecture]
Sea Shanties [book,song,sea,dance]
从这里,我想得到第三个数据帧,它包含df_1的第一列,在它的第二列中包含来自df_2的匹配程序。例:
df_3
Term Program
apple Fruits of the World
panda Animal in the Zoo, Lecture 1
lecture The Old Man and the Sea, Lecture 1
green Fruits of the World
我怎样才能做到这一点呢?这可以通过使用
df.merge
与df.groupby
和df.groupby.agg
来实现。假设您的df1
只有一列:(如果没有,用df1['your\u col\u name']
替换df1.squence()
)
到目前为止你试过什么?你到底在哪里失败了?我得到一个错误,说这里没有通用术语。没有要执行合并的公共列。合并选项:left\u on=None,right\u on=None,left\u index=False,right\u index=False@Alokin你能用你的确切列名更新这个问题吗?如果你能明智地使用列名,这应该是可行的。谢谢。我确实成功地让它工作了,我只需要将步骤分开并更改类型。所以,它是这样的:df2_str=df2_str.explode(“Tags”)df2_str=sf2_str['Tags'].apply(str)df2_str=df2_str=df2_str.groupby(['Tags'])['Programs'].apply(','.join)df2_str=df2_str=df2_str.to_frame().reset_index()完整的结果=df1.join(df2_str.set_index('Term'),on='Term')@Alokin很高兴你能想到这一点。)
df_3
Term Program
apple Fruits of the World
panda Animal in the Zoo, Lecture 1
lecture The Old Man and the Sea, Lecture 1
green Fruits of the World
out = (df2.explode("Tags").merge(df1.squeeze().rename("Tags"))
.groupby("Tags",sort=False)['Program'].agg(','.join).reset_index())
print(out)
Tags Program
0 apple Fruits of the World
1 green Fruits of the World
2 panda Animal in the Zoo,Lecture 1
3 lecture Lecture 1,The Old Man and the Sea