簡體   English   中英

將列值轉換為行並根據另一列的值將它們分組

[英]Transposing column values into rows and grouping them based on value of another column

我有一個看起來像這樣的數據框:

Value     group_id
23        1
28        1
32        1 
....
35        12
23        12
42        12

總共有6個唯一的group_id,每個都有數百個元素。 我想將其轉換為在一行中具有單個' group_id ' 的數據 所以我希望我的數據框看起來像這樣:

value_1 value_2 value_3 group_id
23       28      32      1
....
35       23      42      12

我嘗試使用pandas.melt和pandas.groupby,但未獲得任何結果。

您缺少每個組中'Value'的位置。 我們可以用groupby.cumcount創建它

df.set_index(
    ['group_id', df.groupby('group_id').cumcount() + 1]
).Value.unstack().add_prefix('Value_').reset_index()

   group_id  Value_1  Value_2  Value_3
0         1       23       28       32
1        12       35       23       42

cumcountgroupby一起cumcount以填寫您的'value_'記錄,然后對結果使用.pivot_table

df['val_grp'] = 'value_' + (df.groupby('group_id').cumcount() + 1).astype(str)

pvt = df.pivot_table(index='group_id', columns='val_grp', values='Value')

print(pvt)

打印:

val_grp   value_1  value_2  value_3
group_id                           
1              23       28       32
12             35       23       42

如andrew_reece的注釋中所述,可以通過以下操作在一行中完成:

pvt = df.assign(idx=(df.groupby("group_id").cumcount()+1).astype(str).str.replace("^(.)", "value_\\1", regex=True)).pivot(index="group_id", columns="idx", values="Value")

但是,應該注意的是,這要求使用Pandas 23.0或更高版本,因為這是引入str.replaceregex參數時的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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