Home > Net >  How to access each element of each row when inputting line by line in python
How to access each element of each row when inputting line by line in python

Time:03-22

I have a tab-delimited csv file. My csv file:

    0.227996254681648   0.337028824833703   0.238163571416268   0.183009231781289   0.085746697332588   0.13412895376826
    0.247891283973758   0.335555555555556   0.272129379268419   0.187328622765857   0.085921240923626   0.128372465534807
    0.264761012183693   0.337777777777778   0.245917821271498   0.183211905363232   0.080493183753814   0.122786059549795
    0.30506091846298    0.337777777777778   0.204265153911403   0.208453197418743   0.0715575291087 0.083682658454807
    0.222748815165877   0.337028824833703   0.209714942778068   0.084252659537679   0.142013573559938   0.234672985858848

Now I would like to input each line from the csv file, do something with each element of each row and then do the same thing for the next line and so on.

My code:

lines = []
    with open("/path/testfile.csv") as f:
        csvReader = csv.reader( f, delimiter="\t" )
        for row in csvReader:
            x=row[0] #access first floating number of each line from csv
            y=row[1] #access second floating number of each line from csv
            z=row[2] #access third floating number of each line from csv
            r=row[3] #access fourth floating number of each line from csv
            s=row[4] #access fifth floating number of each line from csv
            t=row[5] #access six floating number of each line from csv
            #do something else with each element

Here I only included print(row[0]) into the for loop:

lines = []
with open("/path/testfile.csv") as f:
    csvReader = csv.reader( f, delimiter="\t" )
    for row in csvReader:
        print(row[0])

But when already trying only print(row[0]), it already prints out all values from the csv file. How can I access each element from each row in python?

CodePudding user response:

Not sure if you are familiar with the pandas library. You could use pandas which will simplify things a lot.

Code

import pandas as pd

df = pd.read_csv('./data/data.csv', delimiter='\t', header=None)
print(df)

Output

          0         1         2         3         4         5
0  0.227996  0.337029  0.238164  0.183009  0.085747  0.134129
1  0.247891  0.335556  0.272129  0.187329  0.085921  0.128372
2  0.264761  0.337778  0.245918  0.183212  0.080493  0.122786
3  0.305061  0.337778  0.204265  0.208453  0.071558  0.083683
4  0.222749  0.337029  0.209715  0.084253  0.142014  0.234673

You can then you can any operation you want on any column. Example :

df[0] = df[0]*10    # Multiply all numbers in the 0th column by 10

CodePudding user response:

just add another loop:

lines = []
with open("/path/testfile.csv") as f:
csvReader = csv.reader( f, delimiter=" " )
for row in csvReader:
    for element in row:
        do_something_with(element)
  • Related