-2

I want to know how to make a .csv list into a python list which I can do plotting and calculating:

I used:

    fpath = r'C:112017\temp\tT.csv'
    with open(fpath,'r') as csvfile:
         reader = csv.reader(csvfile, delimiter=',')
         for row in reader:
             print(list(reader))

it gives me lists like this (which I dont' want):

    [['2014-12-30', '18.34244791666665'], ['2014-12-31', '18.540224913494818'], ['2015-01-01', '18.15729166666666'],......

If I use

    print(row) 

it gives me lists like this (looks better but I still can not use it for calculating):

    ...        
    ['2016-07-27', '20.434809022479584']
    ['2016-07-28', '21.395138886239796']
    ['2016-07-29', '20.81571181284057']
    ['2016-07-30', '20.565711801250778']
    ...

How can I use panda to make a list? Or is there any easier way to achieve this? Is that possible to use something like:

    date = row[0]
    temp = row[1]
    lis = pd.DataFrame(date,temp)

I guess there are some basic mistakes, but I can't fix it by myself. Thank you for your time to help.

Jenny
  • 169
  • 1
  • 3
  • 10
  • `list(reader)` in the loop is strange, as it stops immediately... what is the expected output? because the code you tried works as designed. – Jean-François Fabre Nov 15 '17 at 10:07
  • The output from list(reader) was just like the first output, [['2014-12-30', '18.34244791666665'], ['2014-12-31', '18.540224913494818'], ...] – Jenny Nov 15 '17 at 10:37

3 Answers3

4

There is pandas.read_csv() method which will read the csv file and return a dataframe

Eg:

fpath = r'C:112017\temp\tT.csv'
df = pd.read_csv(fpath, delimiter=',', names=['date', 'temp'])
Arun
  • 1,933
  • 2
  • 28
  • 46
1

I guess you are trying to get the columns as list i.e. a list of dates and temperatures.

fpath = r'C:112017\temp\tT.csv'
with open(fpath,'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    data = list(reader)

date, temp = list(map(list, zip(*data)))
# for python 2 use map(list,zip(*data))
# converting temp to float
temp = list(map(float,temp))
Sagun Shrestha
  • 1,188
  • 10
  • 23
0

in my opinion if you want to perform calculations with data from a .csv file you should consider using pandas and numpy.

import pandas as pd
import numpy as np

# importing dataframe
df = pd.read_csv('filename.csv', delimiter=',')
# check the dataframe
print (df)
dapaz
  • 813
  • 10
  • 16