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

ane*_*kix 6 python python-2.7 pandas

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

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

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

One*_*son 10

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

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')
Run Code Online (Sandbox Code Playgroud)

资料来源:


sir*_*rfz 5

您可以使用该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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)