我想合并两个panda数据帧:
df 1
City | Attraction | X | Z | Y
Somewhere Rainbows 1 2 3
Somewhere Trees 4 4 4
Somewhere Unicorns
df 2
City | Other Column | Also another column
Somewhere Something Something else
通常这样做:
df2.merge(df1[['City', 'Attraction']], left_on='City', right_on='City. how='left']
City | Other Column | Also another column | Attraction
Somewhere Something Something else Rainbows
Somewhere Something Something else Trees
Somewhere Something Something else Unicorns
然而,我想将联接的结果分组到逗号分隔的列表中(或者其他什么(:
City | Other Column | Also another column | Attraction
Somewhere Something Something else Rainbows, Trees, Unicorns
groupby()
和map
:
df2['Attaction'] = df2['City'].map(df1.groupby('City').Attraction.agg(', '.join))