Search code examples
python-3.xlistcsvnames

Python 3 ~ How to take rows from a csv file and put them into a list


I would like to know how to take this file:

name,AGATC,AATG,TATC
Alice,2,8,3
Bob,4,1,5
Charlie,3,2,5

and put it in a list like the following:

[['Alice', 'Bob', 'Charlie'], [2, 8, 3], [4, 1, 5], [3, 2, 5]]

I'm fairly new to python so excuse me my current code looks like this:

file = open(argv[1] , "r")
file1 = open(argv[2] , "r")

text = file1.read()

strl = []


with file:

    csv = csv.reader(file,delimiter=",")

    for row in csv:
        strl = row[1:9]
        break

    df = pd.read_csv(argv[1],header=0)
    df = [df[col].tolist() for col in df.columns]

ignore the strl part its for something else unrelated

but it outputs like this:

[['Alice', 'Bob', 'Charlie'], [2, 4, 3], [8, 1, 2], [3, 5, 5]]

i want it to output like this:

[['Alice', 'Bob', 'Charlie'], [2, 8, 3], [4, 1, 5], [3, 2, 5]]

i would like it to output like the above sample


Solution

  • Using pandas

    In [13]: import pandas as pd
    
    In [14]: df = pd.read_csv("a.csv",header=None)
    
    In [15]: df
    Out[15]:
             0  1  2  3
    0    Alice  2  8  3
    1      Bob  4  1  5
    2  Charlie  3  2  5
    
    In [16]: [df[col].tolist() for col in df.columns]
    Out[16]: [['Alice', 'Bob', 'Charlie'], [2, 4, 3], [8, 1, 2], [3, 5, 5]]
    
    

    Update:

    In [51]: import pandas as pd
    
    In [52]: df = pd.read_csv("a.csv",header=None)
    
    In [53]: data = df[df.columns[1:]].to_numpy().tolist()
    
    In [57]: data.insert(0,df[0].tolist())
    
    In [58]: data
    Out[58]: [['Alice', 'Bob', 'Charlie'], [2, 8, 3], [4, 1, 5], [3, 2, 5]]
    

    Update:

    In [51]: import pandas as pd
    
    In [52]: df = pd.read_csv("a.csv")
    
    In [94]: df
    Out[94]:
          name  AGATC  AATG  TATC
    0    Alice      2     8     3
    1      Bob      4     1     5
    2  Charlie      3     2     5
    
    In [97]: data = df.loc[:, df.columns != 'name'].to_numpy().tolist()
    
    In [98]: data.insert(0, df["name"].tolist())
    
    In [99]: data
    Out[99]: [['Alice', 'Bob', 'Charlie'], [2, 8, 3], [4, 1, 5], [3, 2, 5]]