Python DataFrame:枢轴行作为列
我有来自不同电台的原始文件。当我将它们组合成一个数据框时,我看到三列具有匹配的 id 和名称以及不同的组件。我想将其转换为数据框,其中名称条目成为列名称 代码:
df =
id name component
0 1 Serial Number 103
1 2 Station Name DC
2 1 Serial Number 114
3 2 Station Name CA
4 1 Serial Number 147
5 2 Station Name FL
预期答案:
new_df =
Station Name Serial Number
0 DC 103
1 CA 114
2 FL 147
我的答案:
# Solution1
df.pivot_table('id','name','component')
name
NaN NaN NaN NaN
# Solution2
df.pivot(index=None,columns='name')['component']
name
NaN NaN NaN NaN
我没有得到想要的答案。有什么帮助吗?
I have raw files from different stations. When I combine them into a dataframe, I see three columns with matching id and name with different component. I want to convert this into a dataframe where name entries become the column names
Code:
df =
id name component
0 1 Serial Number 103
1 2 Station Name DC
2 1 Serial Number 114
3 2 Station Name CA
4 1 Serial Number 147
5 2 Station Name FL
Expected answer:
new_df =
Station Name Serial Number
0 DC 103
1 CA 114
2 FL 147
My answer:
# Solution1
df.pivot_table('id','name','component')
name
NaN NaN NaN NaN
# Solution2
df.pivot(index=None,columns='name')['component']
name
NaN NaN NaN NaN
I am not getting desired answer. Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您必须使用相同ID的每2行进行每2行,之后您可以使用枢轴表。
First you have to make every 2 rows with the same id, after that you can use pivot table.
如果您的
序列号
就在站名称
之前:If your
Serial Number
is just beforeStation Name
, you canpivot
onname
columns then combine the every two rows: