1

I want to match a certain string in a CSV file and return the column of the string within the CSV file for example

import csv
data = ['a','b','c'],['d','e','f'],['h','i','j']

for example I'm looking for the word e, I want it to return [1] as it is in the second column.

4 Answers 4

1

The solution using csv.reader object and enumerate function(to get key/value sequence):

def get_column(file, word):
    with open(file) as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            for k,v in enumerate(row):
                if v == word:
                    return k  # immediate value return to avoid further loop iteration

search_word = 'e'
print(get_column("data/sample.csv", search_word))  # "data/sample.csv" is an exemplary file path

The output:

1
Sign up to request clarification or add additional context in comments.

Comments

0

I am not sure why do you need csv in this example.

>>> data = ['a','b','c'],['d','e','f'],['h','i','j']
>>> 
>>> 
>>> string = 'e'
>>> for idx, lst in enumerate(data):
...     if string in lst:
...             print idx

1

4 Comments

works great thanks. Working with a much bigger dataset just needed some guidance on how it worked.
@wolendranh: I think you return the index of a row (instead of column).
@abukaj this is idex of element. It could be same approach for csv colums, a bit modified.
@wolendranh: I know, but it is index of the lst in data, not of string in the lst (which in case of csv data would be the column number).
0

A variation of wolendranh's answer:

>>> data = ['a','b','c'],['d','e','f'],['h','i','j']
>>> word = 'e'
>>> for row in data:
...     try:
...         print(row.index(word))
...     except ValueError:
...         continue

Comments

0

Try the following:

>>> data_list = [['a','b','c'],['d','e','f'],['h','i','j']] 
>>> col2_list = []
>>> 
>>> for d in data_list:
...     col2=d[1]
...     col2_list.append(col2)

So in the end you get a list with all the values of column [1]:

col2_list = ["b","e","i"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.