D.Fig
D.Fig

Reputation: 149

How to get all column values from csv using pandas

I have a table in .csv which contains some random messages:

id,msg
2,start
1,bot
1,run
2,san

I want to get only rows which match certain condition. I managed to do that, but I want to get all cell values of column - msg which match condition.

My code:

df = pd.read_csv('msgs.csv')

# if id==2 and msg contains letter 'a'
p = df[(df['id'] == 2) & (df['msg'].str.contains('a'))]
print(p)

for row in p:
    print(p.iloc[0]['msg'])

When I print(p) my result (which is good) is:

           id msg
1          2  start
5          2    san

And I want to have output like this :

start
san

But when I try to do it with iloc I get only first cell value:

start
start

Probably the solution is easy but I don't know how to get it. Thanks in advance.

Upvotes: 2

Views: 6387

Answers (2)

janu777
janu777

Reputation: 1978

You can always iterate through each row in the csv like this:

for row_number,id,msg in p:
    print(row-number,id,msg)

This will get you the following result:

1 2  start
5 2  san

So if you want just the 'msg' then print this:

for row_number,id,msg in p:
    print(msg)

Hope this helps!

Upvotes: 0

Orest Xherija
Orest Xherija

Reputation: 464

You can always do this:

for x in p['msg'].values:
    print(x)

Upvotes: 4

Related Questions