簡體   English   中英

當某些列相同時合並行使用 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
  1. 對於第 0 行和第 1 行,A 列的結果為“a”,B 列的結果為“xx”(“xx”位於 L 中的“yy”之前)
  2. 對於第 2 行和第 3 行,A 列的結果為“b”,B 列的結果為“yy”(“yy”位於 L 中的“zz”之前)

期望的結果:

    A   B
0   a   xx
1   b   yy

您可以使用pandas.Series.mappandas.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM