+1 vote
in Programming Languages by (56.8k points)
I want to select all rows from a dataframe where the first column has values 'A', 'B', or 'C'. How can I do this?

1 Answer

+2 votes
by (351k points)
selected by
 
Best answer

If the dataframe has a header, you can use loc. If not, you can use iloc.

Suppose your dataframe is df; the following example shows how you can select all rows using loc or iloc:

import pandas as pd

#using iloc

df = df[df.iloc[:, 0].isin(['A', 'B', 'C'])]

#using loc

df = df[df.loc[df['col_name'].isin(['A', 'B', 'C'])]]

The above codes will return a dataframe with rows containing the first column equals A, B, or C.


...