[英]Pandas pivoting string columns impossible?
I am looking to pivot the feature column into column headers.我希望将特征列转换为列标题。
here is the df这是 df
for instance neither of the below work.例如,以下均不工作。 I've tried multiple variations to no avail.
我尝试了多种变体都无济于事。
df.groupby(['feature', 'year'])['value'].unstack(fill_value=0)
df.pivot_table(index='year', columns='feature', values='value')
The end goal would look like this.最终目标看起来像这样。
@ALollz tipped me off on this one. @ALollz 向我透露了这一点。 I should have been using pivot and not pivot_table.
我应该使用pivot而不是pivot_table。
df = pd.pivot(df, values='value', columns='feature', index='year')
You are going from a long layout to wide layout.您正在从长布局变为宽布局。 See the sample below.
请参阅下面的示例。
import pandas as pd
df_long = pd.DataFrame({
"student":
["Andy", "Bernie", "Cindy", "Deb",
"Andy", "Bernie", "Cindy", "Deb",
"Andy", "Bernie", "Cindy", "Deb"],
"school":
["Z", "Y", "Z", "Y",
"Z", "Y", "Z", "Y",
"Z", "Y", "Z", "Y"],
"class":
["english", "english", "english", "english",
"math", "math", "math", "math",
"physics", "physics", "physics", "physics"],
"grade":
[10, 100, 1000, 10000,
20, 200, 2000, 20000,
30, 300, 3000, 30000]
})
df_long
df_long.pivot_table(index=["student", "school"],
columns='class',
values='grade').reset_index()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.