python pd怎么读取指定行列 详细
时间: 2023-05-29 12:02:15 浏览: 633
要读取 pandas 数据框中的特定行和列,可以使用以下方法:
1. 使用.loc[ ] 方法
.loc[ ] 方法允许您根据标签或布尔条件选择特定行和列,语法如下:
```python
df.loc[row_label, column_label]
```
示例:
```python
import pandas as pd
# 创建示例数据框
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]})
# 选择第一行和第二列的值
print(df.loc[0, 'b'])
# 输出:4
# 选择前两行和前两列的所有值
print(df.loc[:1, :'b'])
# 输出:
# a b
# 0 1 4
# 1 2 5
```
2. 使用.iloc[ ] 方法
.iloc[ ] 方法允许您根据整数位置选择特定行和列,语法如下:
```python
df.iloc[row_index, column_index]
```
示例:
```python
import pandas as pd
# 创建示例数据框
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]})
# 选择第一行和第二列的值
print(df.iloc[0, 1])
# 输出:4
# 选择前两行和前两列的所有值
print(df.iloc[:2, :2])
# 输出:
# a b
# 0 1 4
# 1 2 5
```
请注意,在上述示例中,行和列都是从零开始编号的。您可以使用切片或索引选择所需的行和列,或者使用逗号分隔的标签或整数列表选择多个行和列。
阅读全文
相关推荐


















