这是How do I stack rows in a Pandas data frame to get one "long row"?
的后续行动答案有效但删除索引会丢失列类型(它们都变成 object ):
df.stack().reset_index(drop=True).T
我需要保留列类型,最好重命名前缀表示原始行的列,例如:
row_0_column_A, row_0_column_B, ... , row_5_column_A, row_5_column_B ...
示例:
df = pd.DataFrame( [ {'stringy': 'A', 'numerical': 2 }, { 'stringy': 'B', 'numer
ical': 3 } ] )
numerical stringy
0 2 A
1 3 B
期望的输出:
row_0_numerical row_0_stringy row_1_numerical row_1_stringy
0 2 A 3 B
如何?
答案 0 :(得分:1)
你可以pivot
你的桌子:
# create a unique id for all rows and pivot the table
df['id'] = 0
df1 = df.reset_index().pivot(index = 'id', columns = 'index')
# collapse multi index columns to single index
df1.columns = ['_'.join(['row'] + [str(c) for c in col][::-1]) for col in df1.columns.values]
df1
# row_0_numerical row_1_numerical row_0_stringy row_1_stringy
# id
# 0 2 3 A B