[英]Pandas pivot\transpose rows to column headings
Try using pd.wide_to_long
and unstack
:尝试使用pd.wide_to_long
和unstack
:
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
Output:输出:
SetCode G2G L6A
index Name
0 Person1 B B
1 Person1 B C
This is more of a column renaming than pivoting I think.我认为这更像是列重命名而不是旋转。 here is my code这是我的代码
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
produces产生
Name L6A G2G
0 Person1 B B
1 Person1 C B
Thanks to @Sander van den Oord for typing in the dataframe!感谢@Sander van den Oord 输入数据框!
Using pandas.wide_to_long
is the right solution, although one must be cautious with the NaN
values that you have in certain columns.使用pandas.wide_to_long
是正确的解决方案,但必须谨慎对待某些列中的NaN
值。
Therefore, here follows an adaptation of Scott Boston's answer:因此,下面是对 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.