Display selected columns based on field condition in Pandas

Viewed 457

I can get a sorted output of selected columns in Pandas like this:

df[['column A', 'column B', 'column E']].sort_values('column B')

I can get an output containing all columns based on a certain field condition like this:

df[df['File Type'] == 'mp4'].sort_values('column B'))

I can't find the correct syntax for combining both, i.e. getting only the 3 columns in the first statement based on the condition in the second one.

1 Answers

You can use DataFrame.loc for filtering and select specific columns using a list:

df.loc[df['File Type'] == 'mp4', ['column A', 'column B', 'column E']].sort_values('column B')
Related