pandas如何将二维数据帧转换为一维数据帧

xxy*_*yao 2 python-3.x pandas

假设我有一个包含多列的数据框.

    a   b   c
1           
2           
3   
Run Code Online (Sandbox Code Playgroud)

如何将其转换为单列数据帧

1   a
2   a
3   a
1   b
2   b
3   b
1   c
2   c
3   c
Run Code Online (Sandbox Code Playgroud)

请注意,前者是Panel以外的Dataframe

jez*_*ael 6

用途melt:

df = df.reset_index().melt('index', var_name='col').set_index('index')[['col']]
print (df)
      col
index    
1       a
2       a
3       a
1       b
2       b
3       b
1       c
2       c
3       c
Run Code Online (Sandbox Code Playgroud)

或者numpy.repeatnumpy.tileDataFrame构造::

a = np.repeat(df.columns, len(df))
b = np.tile(df.index, len(df.columns))
df = pd.DataFrame(a, index=b, columns=['col'])
print (df)
  col
1   a
2   a
3   a
1   b
2   b
3   b
1   c
2   c
3   c
Run Code Online (Sandbox Code Playgroud)