【问题标题】:How to create a dataframe from a dictionary of un-equal length lists如何从不等长列表的字典中创建数据框
【发布时间】:2020-02-18 16:35:57
【问题描述】:

假设我们有一本字典

dict = {'list1' = ['a','b','e'],
        'list2' = ['a','c'],
        'list3' = ['a','b','d']}

我们如何创建一个其列预定义如下的数据框

         a    b    c    d    e    f
list1    1    1    0    0    1    0
list2    1    0    1    0    0    0
list3    1    1    0    1    0    0

任何建议将不胜感激。 谢谢

【问题讨论】:

    标签: python dataframe dictionary


    【解决方案1】:

    这就是诀窍:

    import pandas as pd
    
    
    def sets_to_dataframe(d, keys):
        rows = []
        index = []
        for label, values in d.items():
            index.append(label)
            rows.append([int(key in values) for key in keys])
        return pd.DataFrame(rows, index=index, columns=keys)
    
    
    d = {
        "list1": ["a", "b", "e"],
        "list2": ["a", "c"],
        "list3": ["a", "b", "d"],
    }
    
    print(
        sets_to_dataframe(
            d, keys=["a", "b", "c", "d", "e", "f"]
        )
    )
    

    输出:

           a  b  c  d  e  f
    list1  1  1  0  0  1  0
    list2  1  0  1  0  0  0
    list3  1  1  0  1  0  0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-16
      • 2015-05-11
      • 2023-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 2020-01-11
      相关资源
      最近更新 更多