【问题标题】:How can I transform a list of tuples into a pandas dataframe so that the first value of each tuple represents a column?如何将元组列表转换为 pandas 数据框,以便每个元组的第一个值代表一列?
【发布时间】:2020-04-13 15:47:33
【问题描述】:

我想转换我的元组列表,以便每个元组的第一个元素代表 2 个不同的列。每个元组的第二个元素应该表示对应于 pandas df 中的列的值。

我当前的元组列表:


list_tuples = [('G', 9.8), ('B', 4.2), ('G', 9.6), ('B', 2.3), ('G',7.6), ('B', 3.1)]

期望的输出:


            G        B   
           9.8      4.2      
           9.6      2.3      
           7.6      3.1      

我目前拥有的代码没有提供所需的输出:


df = pd.DataFrame(list_tuples, columns=['G', 'B'])

【问题讨论】:

    标签: python pandas list nested tuples


    【解决方案1】:

    使用defaultdict 将元组列表转换为列表字典,然后将其传递给DataFrame 构造函数:

    from collections import defaultdict
    
    d = defaultdict(list)
    for a, b in list_tuples:
        d[a].append(b)
    df = pd.DataFrame(d)
    print (df)
         G    B
    0  9.8  4.2
    1  9.6  2.3
    2  7.6  3.1
    

    【讨论】:

      【解决方案2】:

      将其转换为字典,创建数据框并使用 DataFrame.drop_duplicatesDataFrame.bfill 清理它:

      list_tuples = [('G', 9.8), ('B', 4.2), ('G', 9.6), ('B', 2.3), ('G',7.6), ('B', 3.1)]
      
      df = (pd.DataFrame([{col1:val} for col1, val in list_tuples])
              .bfill()
              .drop_duplicates('B')
              .reset_index(drop=True)
           )
      
           G    B
      0 9.80 4.20
      1 9.60 2.30
      2 7.60 3.10
      

      【讨论】:

        猜你喜欢
        • 2020-12-13
        • 1970-01-01
        • 2019-02-14
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        • 2021-05-01
        • 2020-11-07
        • 2017-08-23
        相关资源
        最近更新 更多