【问题标题】:Pandas dtypes dictionary from yaml来自 yaml 的 Pandas dtypes 字典
【发布时间】:2017-11-29 03:57:12
【问题描述】:

我遇到了一个问题,我想从 YAML 文件中加载一个部分以填充 pandas.read_csv dtypes 参数。我的问题是字典中的值有 ' ' 并且 pandas 没有将其识别为数据类型。

Yaml:
  dict: {ITEM_GROUP: object, ITEM: object}

import pandas as pd
with open(yaml_org_path, 'r') as f:
    config = yaml.load(f)
df = pd.read_csv('file.csv', dtypes= config['Yaml']['dict'])

如果我打印这部分 YAML 文件,我会得到:

print(config['Yaml']['dict'])

{'ITEM_GROUP': 'object', 'ITEM': 'object'}

我不确定我是否在 Yaml 文件中正确使用了字典,或者我是否需要使用一些 pyyaml 魔法关键字。我是新手,卡住了,所以提前谢谢你!

【问题讨论】:

    标签: python pandas dictionary yaml


    【解决方案1】:

    这对我有用。您的问题似乎是pd.read_csv 中的参数dtypes 应该是dtype


    import yaml
    
    from io import StringIO
    config = yaml.load(StringIO("""
    Yaml:
      dict: {ITEM_GROUP: object, ITEM: object}
    """))
    
    config['Yaml']['dict']
    # {'ITEM': 'object', 'ITEM_GROUP': 'object'}
    
    pd.read_csv(StringIO("""
    ITEM,ITEM_GROUP
    a,b
    c,d
    """), dtype=config['Yaml']['dict']).dtypes
    #     ^^^^^
    #ITEM          object
    #ITEM_GROUP    object
    #dtype: object
    

    【讨论】:

      猜你喜欢
      • 2018-10-03
      • 2017-01-10
      • 2021-07-10
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 2020-09-01
      • 1970-01-01
      相关资源
      最近更新 更多