jxn
jxn

Reputation: 8025

pandas - write to csv only if column contains certain values

I have a pandas df that looks like this:

df = pd.DataFrame([[1,'hello,bye','USA','3/20/2016  7:00:17 AM'],[2,'good morning','UK','3/20/2016  7:00:20 AM']],columns=['id','text','country','datetime'])

   id          text country               datetime
0   1     hello,bye     USA  3/20/2016  7:00:17 AM
1   2  good morning      UK  3/20/2016  7:00:20 AM

I want to print this output to csv but only if the country column contains 'USA'.

This is what I tried:

if 'USA' in df.country.values:
    df.to_csv('test.csv')

but it prints the entire df to the test.csv file still.

Upvotes: 2

Views: 1394

Answers (1)

TerminalWitchcraft
TerminalWitchcraft

Reputation: 1862

Here is a simple solution to your problem:

df = pd.DataFrame([[1,'hello,bye','USA','3/20/2016  7:00:17 AM'],[2,'good morning','UK','3/20/2016  7:00:20 AM']],columns=['id','text','country','datetime'])

if 'USA' in df.country.tolist():
    df.to_csv('test.csv')

Alternatively, you can also do this by:

df['country'].tolist()

Hope this helps you :)

Upvotes: 2

Related Questions