熊猫将行旋转\转置为列标题

时间:2020-11-10 17:56:08

标签: python pandas

我正在尝试学习熊猫,想知道如何实现以下目标...

example of input and output

以以下内容开头的数据框:

df = pd.DataFrame({
    'Name': ['Person1', 'Person1'],
    'SetCode1': ['L6A', 'L6A'],
    'SetDetail1': ['B', 'C'],
    'SetCode2': ['G2G', 'G2G'],
    'SetDetail2': ['B', 'B'],
})

3 个答案:

答案 0 :(得分:2)

尝试使用pd.wide_to_longunstack

df = pd.DataFrame({
    'Name': ['Person1', 'Person1'],
    'SetCode1': ['L6A', 'L6A'],
    'SetDetail1': ['B', 'C'],
    'SetCode2': ['G2G', 'G2G'],
    'SetDetail2': ['B', 'B'],
})


df_melt = pd.wide_to_long(df.reset_index(), 
                          ['SetCode', 'SetDetail'], 
                          ['index', 'Name'], 
                          'No')

df_out = df_melt.set_index('SetCode', append=True)\
                .reset_index(level=2, drop=True)['SetDetail']\
                .unstack()
df_out

输出:

SetCode       G2G L6A
index Name           
0     Person1   B   B
1     Person1   B   C

答案 1 :(得分:1)

我认为这更像是重命名一列,而不是透视。这是我的代码

code_cols = list(filter(lambda s: s.startswith('SetCode'), df.columns))
det_cols = list(filter(lambda s: s.startswith('SetDetail'), df.columns))
codes = [df[s][0] for s in code_cols]
df.rename(columns = dict(zip(det_cols, codes)), inplace=True)
df.drop(columns = code_cols, inplace=True)
df

产生

    Name    L6A G2G
0   Person1 B   B
1   Person1 C   B

感谢@Sander van den Oord在数据框中输入内容!

答案 2 :(得分:0)

使用pandas.wide_to_long是正确的解决方案,尽管一定要对某些列中的NaN值保持谨慎。

因此,下面是斯科特·波士顿的答案的改编:

import pandas as pd

# I just allowed myself to write 'Person2' instead of 'Person1' at the second row
# of the DataFrame, as I imagine this is what was originally intended in the data,
# but this does not change the method
df = pd.DataFrame({
    'Name': ['Person1', 'Person2'],
    'SetCode1': ['L6A', 'L6A'],
    'SetDetail1': ['B', 'C'],
    'SetCode6': ['U2H', None],
    'SetDetail6': ['B', None],
})
print(df)

      Name SetCode1 SetDetail1 SetCode6 SetDetail6
0  Person1      L6A          B      U2H          B
1  Person2      L6A          C     None       None

# You will need to use reset_index to keep the original index moving forward only if
# the 'Name' column does not have unique values
df_melt = pd.wide_to_long(df, ['SetCode', 'SetDetail'], ['Name'], 'No')

df_out = df_melt[df_melt['SetCode'].notnull()]\
    .set_index('SetCode', append=True)\
    .reset_index(level=1, drop=True)['SetDetail']\
    .unstack()
print(df_out)

SetCode L6A  U2H
Name            
Person1   B    B
Person2   C  NaN