python csv into dictionary

前端 未结 4 1728
感动是毒
感动是毒 2020-12-29 11:44

I am pretty new to python. I need to create a class that loads csv data into a dictionary.

I want to be able to control the keys and value So let say the following c

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-29 12:29

    I know this is a pretty old question, but it's impossible to read this, and not think of the amazing new(ish) Python library, pandas. Its main unit of analysis is a think called a DataFrame which is modelled after the way R handles data.

    Let's say you have a (very silly) csv file called example.csv which looks like this:

    day,fruit,sales
    Monday,Banana,10
    Monday,Orange,20
    Tuesday,Banana,12
    Tuesday,Orange,22
    

    If you want to read in a csv in double-quick time, and do 'stuff' with it, you'd be hard pressed to beat the following code for either brevity or ease of use:

    >>> import pandas as pd
    >>> csv = pd.read_csv('example.csv')
    >>> csv
           day   fruit  sales
    0   Monday  Banana     10
    1   Monday  Orange     20
    2  Tuesday  Banana     12
    3  Tuesday  Orange     22
    >>> csv[csv.fruit=='Banana']
           day   fruit  sales
    0   Monday  Banana     10
    2  Tuesday  Banana     12
    >>> csv[(csv.fruit=='Banana') & (csv.day=='Monday')]
          day   fruit  sales
    0  Monday  Banana     10
    

    In my opinion, this is really fantastic stuff. Never iterate over a csv.reader object again!

提交回复
热议问题