【问题标题】:Convert python dictionary to dataframe with dict values(list) as columns and 1,0 if that column is in dict list将 python 字典转换为数据框,其中 dict 值(列表)作为列,如果该列在 dict 列表中,则为 1,0
【发布时间】:2019-02-07 07:22:08
【问题描述】:

我想从格式为

的字典创建一个数据框
Dictionary_ =  {'Key1': ['a', 'b', 'c', 'd'],'Key2': ['d', 'f'],'Key3': ['a', 'c', 'm', 'n']}

我正在使用

df = pd.DataFrame.from_dict(Dictionary_, orient ='index')

但它会创建自己的列,直到值的最大长度,并将字典的值作为数据帧中的值。

我想要一个 df,其中键作为行,值作为列,如

       a     b      c     d     e     f    m     n 
Key 1  1      1      1    1     0    0    0     0
Key 2  0      0      0    1     0    1    0     0
Key 3  1      0      1    0     0    0    1     1

我可以通过附加 dict 的所有值并创建一个空数据框,其中 dict 键作为行,值作为列,然后遍历每一行以从 dict 获取值并将 1 放在与列匹配的位置,但这会太慢了,因为我的数据有 200 000 行并且 .loc 很慢。我觉得我可以以某种方式使用熊猫假人,但不知道如何在这里应用它。

我觉得会有更聪明的方法来做到这一点。

【问题讨论】:

  • 感谢 anky 以正确的格式编辑问题,这是我的第一个问题,所以我不知道如何正确回答。真的很感激。
  • 没问题,在你的空闲时间你可以通过这个链接:meta.stackexchange.com/questions/22186/…
  • 当然,我会的:)

标签: python pandas dataframe dictionary


【解决方案1】:

如果性能很重要,请使用MultiLabelBinarizer 并通过keysvalues

from sklearn.preprocessing import MultiLabelBinarizer

mlb = MultiLabelBinarizer()
df = pd.DataFrame(mlb.fit_transform(Dictionary_.values()),
                  columns=mlb.classes_, 
                  index=Dictionary_.keys()))
print (df)
      a  b  c  d  f  m  n
Key1  1  1  1  1  0  0  0
Key2  0  0  0  1  1  0  0
Key3  1  0  1  0  0  1  1

另一种方法,但较慢的是创建Series,然后为strings 创建str.join,最后调用str.get_dummies

df = pd.Series(Dictionary_).str.join('|').str.get_dummies()
print (df)
      a  b  c  d  f  m  n
Key1  1  1  1  1  0  0  0
Key2  0  0  0  1  1  0  0
Key3  1  0  1  0  0  1  1

输入 DataFrame 的替代方法 - 使用 pandas.get_dummies,但随后需要对每列聚合 max

df1 = pd.DataFrame.from_dict(Dictionary_, orient ='index')

df = pd.get_dummies(df1, prefix='', prefix_sep='').max(axis=1, level=0)
print (df)
      a  d  b  c  f  m  n
Key1  1  1  1  1  0  0  0
Key2  0  1  0  0  1  0  0
Key3  1  0  0  1  0  1  1

【讨论】:

    【解决方案2】:

    使用get_dummies:

    >>> pd.get_dummies(df).rename(columns=lambda x: x[2:]).max(axis=1, level=0)
          a  d  b  c  f  m  n
    Key1  1  1  1  1  0  0  0
    Key2  0  1  0  0  1  0  0
    Key3  1  0  0  1  0  1  1
    >>> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      相关资源
      最近更新 更多