pandas提供了一个函数实现这个操作:
dataframe.stack()
示例程序:
import pandas as pd
import numpy as npdf = pd.DataFrame(np.random.randint(0, 10, size=(2, 4)), columns=['col_1', "col_2", "col_3", "col_4"]) # 展开 dataframe
series = df.stack() # 展开
series.index = series.index.map('{0[0]}_{0[1]}'.format) # 重新构造multi_index
print(series)
这样对于一个df:
可以展开为Series
类型的数据:
0_col_1 8
0_col_2 4
0_col_3 3
0_col_4 3
1_col_1 6
1_col_2 1
1_col_3 1
1_col_4 7
dtype: int32