![](/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.