pandas Series to Dataframe using Series indexes as columns

后端 未结 4 1467
青春惊慌失措
青春惊慌失措 2021-02-01 14:40

I have a Series, like this:

series = pd.Series({\'a\': 1, \'b\': 2, \'c\': 3})

I want to convert it to a dataframe like this:

          


        
相关标签:
4条回答
  • 2021-02-01 15:25

    you can also try this:

    a = pd.Series.to_frame(series)

    a['id'] = list(a.index)

    Explanation:
    The 1st line convert the series into a single-column DataFrame.
    The 2nd line add an column to this DataFrame with the value same as the index.

    0 讨论(0)
  • 2021-02-01 15:31

    You don't need the transposition step, just wrap your Series inside a list and pass it to the DataFrame constructor:

    pd.DataFrame([series])
    
       a  b  c
    0  1  2  3
    

    Alternatively, call Series.to_frame, then transpose using the shortcut .T:

    series.to_frame().T
    
       a  b  c
    0  1  2  3
    
    0 讨论(0)
  • 2021-02-01 15:35

    You can also try this :

    df = DataFrame(series).transpose()
    

    Using the transpose() function you can interchange the indices and the columns. The output looks like this :

        a   b   c
    0   1   2   3
    
    0 讨论(0)
  • 2021-02-01 15:40

    Try reset_index. It will convert your index into a column in your dataframe.

    df = series.to_frame().reset_index()
    
    0 讨论(0)
提交回复
热议问题