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
python csv to dictionary using csv or pandas module
提问by anekix
I am using Python's csv.DictReader
to 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.reader
but 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 Fieldnames
was 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_dict
method 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_dict
documentation:
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