我有一个特定的情况,我想转换这个 df: 打印 df
Schoolname Attribute Value
0 xyz School Safe 3.44
1 xyz School Cleanliness 2.34
2 xyz School Money 4.65
3 abc School Safe 4.40
4 abc School Cleanliness 4.50
5 abc School Money 4.90
6 lmn School Safe 2.34
7 lmn School Cleanliness 3.89
8 lmn School Money 4.65
我需要采用这种格式,以便我可以将其转换为 numpy 数组以进行线性回归建模。
required_df:
Schoolname Safe Cleanliness Money
0 xyz School 3.44 2.34 4.65
1 abc School 4.40 4.50 4.90
2 lmn School 2.34 3.89 4.65
我知道我们需要执行 groupby('Schoolname') 但无法思考如何让行名称成为列标签以及 required_df 中反射(reflect)的相应值。
我需要这种格式,以便我可以将其转换为 numpy 数组并将其作为我的 X 向量提供给线性回归模型。
最佳答案
您可以使用pd.pivot
In [171]: df.pivot(index='Schoolname', columns='Attribute', values='Value')
Out[171]:
Attribute Cleanliness Money Safe
Schoolname
abc-School 4.50 4.90 4.40
lmn-School 3.89 4.65 2.34
xyz-School 2.34 4.65 3.44
或更易表达的pd.pivot_table
In [172]: pd.pivot_table(df, values='Value', index='Schoolname', columns='Attribute')
Out[172]:
Attribute Cleanliness Money Safe
Schoolname
abc-School 4.50 4.90 4.40
lmn-School 3.89 4.65 2.34
xyz-School 2.34 4.65 3.44
关于python - 如何在groupby之后将数据框中的行值转换为Python中的列标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36259593/