【问题标题】:turning dataframe into dictionary and keeping all values将数据框转换为字典并保留所有值
【发布时间】:2020-01-27 07:22:21
【问题描述】:
import pandas as pd
text = [list(['(1-100-133-1710)']), 'nan', 'nan']
df = pd.DataFrame({'Text': text ,
                   'IDs': ['A11','A11','C11'],
                          }) 
df
    IDs Text
0   A11 [(1-100-133-1710)]
1   A11 nan
2   C11 nan

我有以下df

我的目标是将df 变成字典

所以我尝试以下方法

to_d = dict(zip(df.IDs,df.Text))

我得到以下输出

 {'A11': 'nan', 'C11': 'nan'}

但此输出缺少 df 中行 0 中的键 A11 和值 [(1-100-133-1710)]。理想情况下,我想要以下输出,但 python 字典中不允许重复键

{'A11': '[(1-100-133-1710)]', 'A11': 'nan', 'C11': 'nan'}

因此,我想要以下输出,它将A11 中的两个值组合到一个公共值列表中,该列表保留相同的键 A11

{'A11': '[[(1-100-133-1710)]', 'nan'], 'C11': 'nan'}

如何获得我想要的输出?

【问题讨论】:

    标签: python-3.x string pandas list dictionary


    【解决方案1】:

    所以我们可以使用to_dict

    df.groupby('IDs').Text.apply(list).to_dict()
    Out[431]: {'A11': [['(1-100-133-1710)'], 'nan'], 'C11': ['nan']}
    

    【讨论】:

      猜你喜欢
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-05
      • 2019-08-02
      • 1970-01-01
      • 2021-06-19
      相关资源
      最近更新 更多