![](/img/trans.png)
[英]How to merge rows when data when some columns are the same using Pandas Python
[英]Merging rows when some columns are the same using Pandas Python
现在我有一个 dataframe,我想合并行。 值 B 由列表中字符串的顺序确定 L = ['xx','yy','zz']
A B
0 a xx
1 a yy
2 b zz
3 b yy
期望的结果:
A B
0 a xx
1 b yy
您可以使用pandas.Series.map
和pandas.DataFrame.groupby
:
df['C'] = df['B'].map(dict(zip(L,range(len(L)))))
df.groupby('A')[['B','C']].apply(lambda x: x.iloc[x["C"].argmin()]['B'])
#A
#a xx
#b yy
您可以使用pandas.Categorical
获得相同的结果:
df['B'] = pd.Categorical(df['B'], categories = L, ordered = True)
df.groupby('A').min()
# B
#A
#a xx
#b yy
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.