繁体   English   中英

如何在 Python 中将 csv 文件转换为字典?

[英]How to convert a csv file to a Dictionary in Python?

我有一个 csv 文件,其中包含创建 yaml 文件的配置信息(最终所需的结果)。 首先,我试图将 csv 文件的每一行转换为字典,然后我可以使用 yaml.dump(Created_Dictionary) 轻松地将字典转换为 yaml 文件

示例输入文件 (test.csv):

fieldname|type|allowed|coerce
field_A|String|10,20,30|to_str
field_B|Integer||to_int

我使用熊猫库的源代码:

df = pd.read_csv("test.csv", "|")
df_to_dict = df.to_dict(orient='records')
print(df_to_dict) # print the dictionary

test_yaml = yaml.dump(df_to_dict)
print(test_yaml) # print the yaml file

我得到的字典输出(df_to_dict):

[{'fieldname': 'field_A', 'type': 'String', 'allowed': '10,20,30'}, {'fieldname': 'field_B', 'type': 'Integer', 'allowed': nan}]

我为 yaml (test_yaml) 得到的输出:

- allowed: 10,20,30
  fieldname: field_A
  type: String
- allowed: .nan
  fieldname: field_B
  type: Integer

所需的字典输出(df_to_dict)是:

[
  {'field_A':
          {'type': 'String', 'allowed': '10,20,30', 'coerce': to_str}
       },
  {'field_B':
          {'type': 'String',  'allowed': '', 'coerce': to_int}
       } 
]

所需的 yaml 输出(test_yaml)是:

field_A:
  type: String
  allowed: 
  - '10'
  - '20'
  - '30'
  coerce: to_str
field_B:
  type: Integer
  allowed:
  coerce: to_int

我看到变量 df_to_dict 是一个字典列表。 我是否必须遍历每个列表项,然后为每一行构建字典? 我不明白正确的方法。 任何帮助表示赞赏。

尝试:

my_dict = df.set_index("fieldname").to_dict("index")
test_yaml = yaml.dump(my_dict, sort_keys=False)

>>> print(test_yaml)
field_A:
  allowed: 10,20,30
  type: String
field_B:
  allowed: .nan
  type: Integer

你想玩弄你的熊猫数据帧的索引。

>>> df = pd.read_csv("test.csv", sep="|", index_col=0)
>>> df
              type   allowed
fieldname                   
field_A     String  10,20,30
field_B    Integer       NaN
>>> df.to_dict(‘index’) # returns dict like {index -> {column -> value}}
{'field_A': {'type': 'String', 'allowed': '10,20,30'}, 'field_B': {'type': 'Integer', 'allowed': nan}}
>>> print(yaml.dump(df.to_dict(‘index’)))
field_A:
  allowed: 10,20,30
  type: String
field_B:
  allowed: .nan
  type: Integer

您必须处理自定义转储或过滤器的.nan

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html?highlight=to_dict#pandas.DataFrame.to_dict

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

如果您不需要 Pandas,并且在您的描述或示例中我认为不需要它,请使用 Python 的内置csv库及其DictReader类。

import csv

with open('sample.csv', newline='') as f:
    reader = csv.DictReader(f, delimiter='|')
    for row in reader:
        fname = row['fieldname']
        yaml_d = {fname: row}          # "index" row by fieldname
        del yaml_d[fname]['fieldname'] # remove now-extraneous fieldname from row
        print(yaml_d)

让我:

{'field_A': {'type': 'String', 'allowed': '10,20,30'}}
{'field_B': {'type': 'Integer', 'allowed': ''}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM