Home > Back-end >  Reading columns of data for every point in a csv file in Python
Reading columns of data for every point in a csv file in Python

Time:07-05

I want to read the second column of data with the title nodes and assign to a variable with the same name for each point of t1.

import csv

with open('Data_10x10.csv', 'r') as f:
    csv_reader = csv.reader(f)

The data looks like

enter image description here

CodePudding user response:

csv_reader = csv.reader(f) is a Generator. So you can skip the headers by execute heading = next(csv_reader).

I would just use a dictionary data_t1 for storing node data with key name of column t1.

Try below one.

import csv

with open('Data_10x10.csv', 'r') as f:
    data_t1={}
    csv_reader = csv.reader(f)
    # Skips the heading
    heading = next(csv_reader)

    for row in csv_reader:
        data_t1[row[0]] = row[1]

Accessing data (key should be value of you t1 column, in this case '0', '1' etc.) print(data_t1['0']) print(data_t1['1'])

If you want to create dynamic variables with the same name for each point of t1 It is really bad idea. If your csv has lot of rows maybe millions, it will create millions of variables. So use dictionary with key and values.

  • Related