Convert pandas Series to DataFrame

前端 未结 6 1010
长情又很酷
长情又很酷 2020-11-27 11:08

I have a Pandas series sf:

email
email1@email.com    [1.0, 0.0, 0.0]
email2@email.com    [2.0, 0.0, 0.0]
email3@email.com    [1.0, 0.0, 0.0]
email4@email.com         


        
6条回答
  •  我在风中等你
    2020-11-27 11:41

    Series.reset_index with name argument

    Often the use case comes up where a Series needs to be promoted to a DataFrame. But if the Series has no name, then reset_index will result in something like,

    s = pd.Series([1, 2, 3], index=['a', 'b', 'c']).rename_axis('A')
    s
    
    A
    a    1
    b    2
    c    3
    dtype: int64
    

    s.reset_index()
    
       A  0
    0  a  1
    1  b  2
    2  c  3
    

    Where you see the column name is "0". We can fix this be specifying a name parameter.

    s.reset_index(name='B')
    
       A  B
    0  a  1
    1  b  2
    2  c  3
    

    s.reset_index(name='list')
    
       A  list
    0  a     1
    1  b     2
    2  c     3
    

    Series.to_frame

    If you want to create a DataFrame without promoting the index to a column, use Series.to_frame, as suggested in this answer. This also supports a name parameter.

    s.to_frame(name='B')
    
       B
    A   
    a  1
    b  2
    c  3
    

    pd.DataFrame Constructor

    You can also do the same thing as Series.to_frame by specifying a columns param:

    pd.DataFrame(s, columns=['B'])
    
       B
    A   
    a  1
    b  2
    c  3
    

提交回复
热议问题