簡體   English   中英

Pandas 樞軸\\轉置行到列標題

[英]Pandas pivot\transpose rows to column headings

我正在嘗試學習熊貓並想知道如何實現以下目標...

輸入輸出示例

數據幀開始:

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

嘗試使用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

我認為這更像是列重命名而不是旋轉。 這是我的代碼

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 輸入數據框!

使用pandas.wide_to_long是正確的解決方案,但必須謹慎對待某些列中的NaN值。

因此,下面是對 Scott Boston 的回答的改編:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM