2

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.

2 Answers 2

4

You can always do this:

for x in p['msg'].values:
    print(x)
Sign up to request clarification or add additional context in comments.

Comments

0

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!

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.