使用来自 Groupby Python 的多列进行数据透视 Table
Pivot Table with multi column from Groupby Python
对(id,性别和工作)进行groupby操作后,我有这个:
id geneder job salary
22 male engineer 100
doctor 120
...
female engineer 90
doctor 100
...
23 male engineer 200
doctor 150
...
female engineer 80
doctor 100
由此我想创建类似的东西:
id m_engineer m_doctor ... f_engineer f_doctor
22 100 120 90 100
23 200 150 80 100
我尝试使用数据透视表,但仍然出现错误。
有什么想法吗?
您需要创建一个可以旋转的新列,例如
(grouped_df
.reset_index()
.assign(gender_job = lambda df: df['gender'].str[0] + '_' + df['job'])
.pivot('id', 'gender_job', 'salary'))
对(id,性别和工作)进行groupby操作后,我有这个:
id geneder job salary
22 male engineer 100
doctor 120
...
female engineer 90
doctor 100
...
23 male engineer 200
doctor 150
...
female engineer 80
doctor 100
由此我想创建类似的东西:
id m_engineer m_doctor ... f_engineer f_doctor
22 100 120 90 100
23 200 150 80 100
我尝试使用数据透视表,但仍然出现错误。 有什么想法吗?
您需要创建一个可以旋转的新列,例如
(grouped_df
.reset_index()
.assign(gender_job = lambda df: df['gender'].str[0] + '_' + df['job'])
.pivot('id', 'gender_job', 'salary'))