How to convert Dataframe into Series?

前端 未结 6 1966
隐瞒了意图╮
隐瞒了意图╮ 2021-01-13 23:33

I want to convert N columns into one series. How to do it effectively?

Input:

    0   1   2   3
0  64  98  47  58
1  80  94  81  46
2  18  43  79  84         


        
相关标签:
6条回答
  • 2021-01-13 23:56

    You can also use Series class and .values attribute:

    pd.Series(df.values.T.flatten())
    

    Output:

    0     64
    1     80
    2     18
    3     57
    4     98
    5     94
    6     43
    7     35
    8     47
    9     81
    10    79
    11    81
    12    58
    13    46
    14    84
    15    31
    dtype: int64
    
    0 讨论(0)
  • 2021-01-14 00:07

    You can use unstack

    pd.Series(df.unstack().values)
    
    0 讨论(0)
  • 2021-01-14 00:11

    Here's yet another short one.

    >>> pd.Series(df.values.ravel(order='F'))                                                                                                               
    >>> 
    0     64
    1     80
    2     18
    3     57
    4     98
    5     94
    6     43
    7     35
    8     47
    9     81
    10    79
    11    81
    12    58
    13    46
    14    84
    15    31
    dtype: int64
    
    0 讨论(0)
  • 2021-01-14 00:12

    you need np.flatten

    pd.Series(df.values.flatten(order='F'))
    
    out[]
    0     64
    1     80
    2     18
    3     57
    4     98
    5     94
    6     43
    7     35
    8     47
    9     81
    10    79
    11    81
    12    58
    13    46
    14    84
    15    31
    dtype: int64
    
    0 讨论(0)
  • 2021-01-14 00:15

    Use pd.melt() -

    df.melt()['value']
    

    Output

    0     64
    1     80
    2     18
    3     57
    4     98
    5     94
    6     43
    7     35
    8     47
    9     81
    10    79
    11    81
    12    58
    13    46
    14    84
    15    31
    Name: value, dtype: int64
    
    0 讨论(0)
  • 2021-01-14 00:15
    df.T.stack().reset_index(drop=True)
    

    Out:

    0     64
    1     80
    2     18
    3     57
    4     98
    5     94
    6     43
    7     35
    8     47
    9     81
    10    79
    11    81
    12    58
    13    46
    14    84
    15    31
    dtype: int64
    
    0 讨论(0)
提交回复
热议问题