【问题标题】:Obtain a pandas dataframe with two columns from a python list从 python 列表中获取具有两列的 pandas 数据框
【发布时间】:2022-01-18 09:45:43
【问题描述】:

我有一个类似的列表

list1=['wwe', '0.99,', 'aew', '0.80,', 'ufc', '1,', 'tna', '0.45,', 'wwf', '1,', 'ring of honor', '0.6,']

我正在尝试将列表推送到 pandas 数据框中,以便我的数据框如下所示:

shows          ratings
wwe            0.99
aew            0.80
ufc            1
tna            0.45
wwf            1
ring of honor  0.6

我尝试了不同的方法来获取这个数据框,但没有得到它,我该如何实现呢?

【问题讨论】:

    标签: python pandas list


    【解决方案1】:

    使用DataFrame 构造函数和reshape,这里-1 由numpy 计数,然后删除逗号并转换为列ratings 的浮点数:

    df = pd.DataFrame(np.reshape(list1, (-1,2)), columns=['shows','ratings'])
    
    df['ratings'] = df['ratings'].str.strip(',').astype(float)
    print (df)
               shows  ratings
    0            wwe     0.99
    1            aew     0.80
    2            ufc     1.00
    3            tna     0.45
    4            wwf     1.00
    5  ring of honor     0.60
    

    【讨论】:

    • 这很好,谢谢。
    【解决方案2】:
    import pandas as pd
    list1=['wwe', '0.99,', 'aew', '0.80,', 'ufc', '1,', 'tna', '0.45,', 'wwf', '1,', 'ring of honor', '0.6,']
    
    
    col1 = list1[::2]
    col2 = list1[1::2]
    
    # create dataframe from col1 and col2 
    df = pd.DataFrame({'shows':col1, 'ratings':col2})
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-06
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 2016-03-13
      • 2016-06-01
      • 2014-04-23
      相关资源
      最近更新 更多