【问题标题】:How to create a dictionary from Excel with list as values in pandas?如何从 Excel 创建一个字典,其中列表作为 Pandas 中的值?
【发布时间】:2021-11-18 23:30:27
【问题描述】:

INPUT- 这是一张 Excel 表格

DatasetName Fields
Table_1 Column1
Table_1 Column2
Table_1 Column3
Table_1 Column4
Table_2 Column1
Table_2 Column2
Table_2 Column3
Table_2 Column4
Table_3 Column1
Table_3 Column2
Table_3 Column3
Table_3 Column4
输出-
{'Table_1' : ['Column1','Column2','Column3','Column4'] ,
 'Table_2' : ['Column1','Column2','Column3','Column4'] ,
 'Table_3' : ['Column1','Column2','Column3','Column4'] }

【问题讨论】:

  • 您能补充一下到目前为止您尝试过的内容吗?
  • Stack Overflow 无意取代现有的教程或文档。除此之外,与您的想法相反,它不是免费的编码服务。您应该发送honest attempt at the solution,然后然后仅在遇到问题时才提出具体问题。

标签: python pandas dictionary


【解决方案1】:

利用强大的 Pandas 数据分组和聚合功能:

只需一行.groupby() + .agg() + to_dict() 即可轻松完成,如下:

import pandas as pd

# read the Excel into dataframe `df`
df = pd.read_excel('my_excel.xlsx')

# generate dict 
dict_out = df.groupby('DatasetName')['Fields'].agg(list).to_dict()

结果:

print(dict_out)

{'Table_1 ': ['Column1', 'Column2', 'Column3', 'Column4'],
 'Table_2': ['Column1', 'Column2', 'Column3', 'Column4'],
 'Table_3': ['Column1', 'Column2', 'Column3', 'Column4']}

【讨论】:

    【解决方案2】:

    试试:

    import pandas as pd
    
    df = pd.read_csv('my_file.csv')
    # Get the unique dataset names 
    names = df['DatasetName'].unique()
    
    result = {}
    # Loop over the names, get the corresponding values, store them as a list
    for name in names:
        x = df.loc[df['DatasetName'] == name]
        vals = x['Fields'].tolist()
        result[name] = vals
    
    print(result)
    

    【讨论】:

      猜你喜欢
      • 2017-07-05
      • 1970-01-01
      • 2016-10-05
      • 1970-01-01
      • 2021-06-20
      • 2021-05-14
      • 2016-02-14
      • 2016-09-13
      • 1970-01-01
      相关资源
      最近更新 更多