简体   繁体   English

Python Dataframe:pivot 行作为列

[英]Python Dataframe: pivot rows as columns

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.当我将它们组合成 dataframe 时,我看到三列具有匹配的 ID 和名称以及不同的组件。 I want to convert this into a dataframe where name entries become the column names Code:我想将其转换为 dataframe,其中名称条目成为列名代码:

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?有什么帮助吗?

First you have to make every 2 rows with the same id, after that you can use pivot table.首先,您必须使每 2 行具有相同的 ID,之后您可以使用 pivot 表。

import pandas as pd

df = pd.DataFrame({'id': ["1", "2", "1", "2", "1", "2"],
                    'name': ["Serial Number", "Station Name", "Serial Number", "Station Name", "Serial Number", "Station Name"],
                   'component': ["103", "DC", "114", "CA", "147", "FL"]})
new_column = [x//2+1 for x in range(len(df))]
df["id"] = new_column

df = df.pivot(index='id',columns='name')['component']

If your Serial Number is just before Station Name , you can pivot on name columns then combine the every two rows:如果您的Serial Number就在Station Name之前,您可以在name列上pivot然后合并每两行:

df_ = df.pivot(columns='name', values='component').groupby(df.index // 2).first()
print(df_)

name Serial Number Station Name
0              103           DC
1              114           CA
2              147           FL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM