[英]python csv to dictionary using csv or pandas module
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. 我正在使用Python的csv.DictReader
从CSV文件中读取值,以创建字典,其中键是CSV的第一行或头,其他行是值。 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. 我尝试使用csv.reader
但我不认为它具有此功能。 Maybe this can be achieved using pandas? 也许可以使用熊猫来实现?
Here is the code I was using with CSV module where Fieldnames
was the keys that I wanted to retain in my dict. 这是我在CSV模块中使用的代码,其中Fieldnames
是我想保留在字典中的键。 I realized it isn't used for what I described above. 我意识到它没有用于我上面描述的内容。
import csv
with open(target_path+target_file) as csvfile:
reader = csv.DictReader(csvfile,fieldnames=Fieldnames)
for i in reader:
print i
You can do this very simply using 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: 资料来源:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.