How to select specific rows and columns in pandas DataFrame?
Published on Aug. 22, 2023, 12:17 p.m.
To select specific rows and columns in a pandas DataFrame, you can use the .loc[]
or .iloc[]
operators followed by selection brackets []
. The .loc[]
operator is used for label-based indexing, while .iloc[]
is used for integer-based indexing.
For example, to select specific rows and columns by label names, you can use:
df.loc[row_labels, column_labels]
And to select specific rows and columns by integer positions, you can use:
df.iloc[row_positions, column_positions]
Here, row_labels
and column_labels
are lists of label names, and row_positions
and column_positions
are lists of integer positions.
For example, to select rows with index labels “A” and “C” and columns with label names “col1” and “col3”, you can use:
df.loc[["A", "C"], ["col1", "col3"]]
And to select the first two rows and the first three columns, you can use:
df.iloc[:2, :3]
I hope this helps! Let me know if you have any other questions.