pandas python csv到字典使用csv或pandas模块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44357380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:43:52  来源:igfitidea点击:

python csv to dictionary using csv or pandas module

pythonpython-2.7pandas

提问by anekix

I am using Python's csv.DictReaderto read in values from a CSV file to create a dictionary where keys are first row or headers in the CSV and other rows are values. It works perfectly as expected and I am able to get a dictionary, but I only want certain keys to be in the dictionary rather than all of the column values. What is the best way to do this? I tried using csv.readerbut I don't think it has this functionality. Maybe this can be achieved using pandas?

我正在使用 Pythoncsv.DictReader从 CSV 文件中读取值以创建一个字典,其中键是 CSV 中的第一行或标题,其他行是值。它按预期完美运行,我可以获得字典,但我只希望某些键在字典中,而不是所有列值。做这个的最好方式是什么?我试过使用,csv.reader但我认为它没有这个功能。也许这可以使用Pandas来实现?

Here is the code I was using with CSV module where Fieldnameswas the keys that I wanted to retain in my dict. I realized it isn't used for what I described above.

这是我在 CSV 模块中使用的代码,其中Fieldnames我想在字典中保留的键。我意识到它不适用于我上面描述的内容。

import csv
with open(target_path+target_file) as csvfile:
    reader = csv.DictReader(csvfile,fieldnames=Fieldnames)
    for i in reader:
        print i

回答by Onel Harrison

You can do this very simply using pandas.

您可以使用Pandas非常简单地做到这一点。

import pandas as pd

# get only the columns you want from the csv file
df = pd.read_csv(target_path + target_file, usecols=['Column Name1', 'Column Name2'])
result = df.to_dict(orient='records')

Sources:

资料来源:

回答by sirfz

You can use the to_dictmethod to get a list of dicts:

您可以使用该to_dict方法获取字典列表:

import pandas as pd

df = pd.read_csv(target_path+target_file, names=Fieldnames)

records = df.to_dict(orient='records')

for row in records:
    print row

to_dictdocumentation:

to_dict文档:

In [67]: df.to_dict?
Signature: df.to_dict(orient='dict')
Docstring:
Convert DataFrame to dictionary.

Parameters
----------
orient : str {'dict', 'list', 'series', 'split', 'records', 'index'}
    Determines the type of the values of the dictionary.

    - dict (default) : dict like {column -> {index -> value}}
    - list : dict like {column -> [values]}
    - series : dict like {column -> Series(values)}
    - split : dict like
      {index -> [index], columns -> [columns], data -> [values]}
    - records : list like
      [{column -> value}, ... , {column -> value}]
    - index : dict like {index -> {column -> value}}

      .. versionadded:: 0.17.0

    Abbreviations are allowed. `s` indicates `series` and `sp`
    indicates `split`.

Returns
-------
result : dict like {column -> {index -> value}}
File:      /usr/local/lib/python2.7/dist-packages/pandas/core/frame.py
Type:      instancemethod