0

I have a CSV file, I want to iterate each row of only one specific column.

Let's say, the column name is "phrase", there are 1000 rows in this column as follows:

ID phrase
1 apple
2 banana
... ...

How can I iterate each cell in this column?

I have tried to use:

df = pd.read_csv('myfile.csv', usecols=[1])
for row in df:
    print(row)

I only get value of the first row of this column, not iterate each row, as follows:

Current output:
phrase
Desired output:
phrase # with or without this one are all OK
apple
banana

Does anyone know how can I get the desired result? Thanks!

3
  • Why do you convert row to list? list('abc') is ['a', 'b', 'c']. Also, do you -really- need pandas? can you just use the csv module directly? Also2, you can just do df.phrase.tolist() Commented Feb 10, 2022 at 18:30
  • Hi @DeepSpace, thanks for your comment. I actually do not have to use pandas, if so, which csv module I can use? It is my first time to deal with csv file. Commented Feb 10, 2022 at 18:32
  • I wrote a proper answer Commented Feb 10, 2022 at 18:37

1 Answer 1

1

Don't convert row to list. list('abc') is ['a', 'b', 'c'].

The simplest way to achieve this is with df.phrase.tolist():

import pandas as pd

df = pd.read_csv('myfile.csv')
print(df.phrase.tolist())

outputs

['apple', 'banana']

Since you commented that you don't actually have to use pandas, this can be done with the built-in csv module which might be a bit less overwhelming for a beginner:

import csv

with open('myfile.csv') as f:
    reader = csv.DictReader(f)
    phrases = [line['phrase'] for line in reader]

print(phrases)

Also outputs

['apple', 'banana']
Sign up to request clarification or add additional context in comments.

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.