我有以下pandas数据框架
id category counts_mean
0 8 a 23
1 8 b 22
2 8 c 23
3 8 d 30
4 9 a 40
5 9 b 22
6 9 c 11
7 9 d 10
....
我想按id进行分组,然后将类别列进行转置,得到这样的结果:我尝试了不同的groupby和pivot,但我不确定groupby的聚合参数应该是什么。
id a b c d
0 8 23 22 23 30
1 9 40 22 11 10
我尝试了groupby和pivot的不同方法 但我不确定groupby的聚合参数应该是什么... ...
与其使用groupby和pivot,你只需要使用pivot函数和设置参数(索引,列,值)来重新塑造你的DataFrame。
#Creat the DataFrame
data = {
'id': [8,8,8,8,9,9,9,9],
'catergory': ['a','b','c','d','a','b','c','d'],
'counts_mean': [23,22,23,30,40,22,11,10]
}
df = pd.DataFrame(data)
# Using pivot to reshape the DF
df_reshaped = df.pivot(index='id',columns='catergory',values = 'counts_mean')
print(df_reshaped)
output:
catergory a b c d
id
8 23 22 23 30
9 40 22 11 10