深度阅读

How to select specific rows and columns in pandas DataFrame?

作者
作者
2023年08月22日
更新时间
9.84 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。