sdgd
sdgd

Reputation: 733

Putting the data into a list after spiltting the CSV file - Python

I have a csv file which I am splitting with delimiter ','. My target is to iterate through the first column of the entire file and if it matches with the word I have, then I need to have the subsequent values of that particular row into different lists.

Example:

AAA,man,2300,
AAA,woman,3300,
BBB,man,2300,
BBB,man,3300,
BBB,man,2300,
BBB,woman,3300,
CCC,woman,2300,
CCC,man,3300,
DDD,man,2300,

My code:

import csv
datafile = "test.txt"    
with open('C:/Users/Dev/Desktop/TEST/Details/'+datafile, 'r') as f:
            reader = csv.reader(f,delimiter=',')
            for row in reader:
            print (rows)

If I search for a value BBB, I want to have the rest of the details of the rows into 3 different lists. (CSV file will always have only 4 columns; the fourth column might be empty sometimes, so we just leave it with a comma)

Sample:

list1 = [man, man, man, woman]
list2 = [2300, 3300, 2300, 3300]
list3 = [ , , , ,]

How can I do this?

Upvotes: 1

Views: 59

Answers (4)

Anton vBR
Anton vBR

Reputation: 18916

Try it with pandas:

import pandas as pd
df = pd.read_csv('path/to/file',sep=',',header=None)

Now just use:

list1,list2,list3 = df[df[0] == "BBB"].T.values.tolist()

Example df:

df = pd.DataFrame(dict(col1=["AAA","BBB","BBB"],
                  col2=[1,2,3],
                  col3=[4,5,6]))

Outputs:

(['BBB', 'BBB'], [2, 3], [5, 6]) #list1,list2,list3

Upvotes: 2

guyd
guyd

Reputation: 743

I'll ignore the part you read data from csv file.

let us begin with a list ( 2d array ). construct a for loop to to search only row1 for your condition - for your example result vector=[1,2,7,8,9]. this vector contains list of indices meeting your condition.

now to get the "filtered" list justmake another for loop extracting all other rows indices result_vector.

Upvotes: 1

Yoda
Yoda

Reputation: 445

Answer for your question is there in your statement: "If I search for a value, say BBB, i want to have the rest of the details of the rows into 3 different lists"

Create empty list:-

list1=[]
list2=[]
list3=[]

Append values into those list:-

for row in reader:
    if ( row[0] == "BBB" ):
        list1.append(row[1])
        list2.append(row[2])
        list3.append(row[3])

Upvotes: 1

theBrainyGeek
theBrainyGeek

Reputation: 584

You can initialize three empty list variables and then, in the loop of rows, if c1 matches your value, append the consequent columns to the list. Edit: OR use pandas at Anton VBR has answered.

Upvotes: 1

Related Questions