ccsv
ccsv

Reputation: 8649

Pandas selecting data with specific conditions

I have a dataframe that looks like this:

item    storage
record  paper
record  laptop
record  desktop
file    laptop
file    paper
file    paper
record  desktop
file    desktop

If I want a new data frame with 2 criteria such as 'record' in the item column and 'laptop' or desktop in the storage column is there an easier way to select this dataset rather than:

df1=df[(df['item'] == 'record') &  (df['storage'] == 'laptop')]
df2=df[(df['item'] == 'record') &  (df['storage'] == 'desktop')]
df3= pd.concat([df1, df2], axis=1)

Is there a shorter way to do this something in one line like:

df3=df[(df['item'] == 'record') &  (df['storage'] == 'laptop' or 'desktop')] #This does not work

Upvotes: 2

Views: 403

Answers (1)

behzad.nouri
behzad.nouri

Reputation: 77941

you can change one of the conditions to .isin:

>>> df['storage'].isin(['laptop', 'desktop'])

so:

>>> df[(df['item'] == 'record') & (df['storage'].isin(['laptop', 'desktop']))]
     item  storage
1  record   laptop
2  record  desktop
6  record  desktop

Upvotes: 3

Related Questions