Converting pandas.core.series.Series to dataframe with appropriate column values python

后端 未结 2 448
南方客
南方客 2020-12-30 04:13

i\'m running a function in which a variable is of pandas.core.series.Series type.

type of the series shown below.



        
相关标签:
2条回答
  • 2020-12-30 04:42

    Sample:

    import pandas as pd
    
    df = pd.DataFrame({'Name': ['Will','John','John','John','Alex'],
                       'Payment':  [15, 10, 10, 10, 15],
                       'Duration':    [30, 15, 15, 15, 20]})
    

    You can print by converting the series/dataframe to string:

    > print (df.to_string())
       Duration  Name  Payment
    0        30  Will       15
    1        15  John       10
    2        15  John       10
    3        15  John       10
    4        20  Alex       15
    
    > print (df.iloc[1].to_string())
    Duration      15
    Name        John
    Payment       10
    
    0 讨论(0)
  • 2020-12-30 04:49

    You was very close, first to_frame and then transpose by T:

    s = pd.Series([1159730, 1], index=['product_id_y','count'], name=6159402)
    print (s)
    product_id_y    1159730
    count                 1
    Name: 6159402, dtype: int64
    
    df = s.to_frame().T
    print (df)
             product_id_y  count
    6159402       1159730      1
    

    df = s.rename(None).to_frame().T
    print (df)
       product_id_y  count
    0       1159730      1
    

    Another solution with DataFrame constructor:

    df = pd.DataFrame([s])
    print (df)
             product_id_y  count
    6159402       1159730      1
    

    df = pd.DataFrame([s.rename(None)])
    print (df)
       product_id_y  count
    0       1159730      1
    
    0 讨论(0)
提交回复
热议问题