DataFrame中df.iloc
时间: 2023-06-17 16:06:28 浏览: 57
df.iloc 是 Pandas 中的一个用于按位置选择数据的方法,它可以通过行号和列号来选择 DataFrame 中的元素。它的语法为:
```python
df.iloc[row_index, column_index]
```
其中,row_index 和 column_index 可以是整数、整数列表、整数范围或布尔数组。
例如,选择第一行和第二列的元素:
```python
df.iloc[0, 1]
```
选择前三行和前两列的元素:
```python
df.iloc[:3, :2]
```
选择第二行和第四行的元素:
```python
df.iloc[[1, 3], :]
```
选择第一列和第四列的元素:
```python
df.iloc[:, [0, 3]]
```
总之,df.iloc 可以让我们以位置为基准来选择 DataFrame 中的元素。
相关问题
dataframe.iloc.values
The attribute `values` in the `iloc` property of a Pandas DataFrame returns a NumPy array representation of the DataFrame's values.
For example, suppose we have a DataFrame `df`:
```
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
```
We can access the values of the DataFrame using the `iloc` property:
```
values = df.iloc.values
```
This will return a NumPy array of the same shape as the DataFrame:
```
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
```
Note that the `values` attribute returns a copy of the data, not a view. Therefore, any modifications made to the NumPy array will not affect the original DataFrame.
dataframe.iloc
`dataframe.iloc` 是 pandas 库中的一个用于按照位置选择数据的方法。它的全称是 "integer location based indexing",即基于整数位置的索引。
`dataframe.iloc` 的语法为:`dataframe.iloc[row_index, column_index]`。其中,`row_index` 和 `column_index` 都可以是整数、整数列表或整数切片。
例如,假设有以下数据框:
```
import pandas as pd
data = {
'name': ['Alice', 'Bob', 'Charlie', 'David', 'Emily'],
'age': [25, 32, 18, 47, 22],
'gender': ['F', 'M', 'M', 'M', 'F']
}
df = pd.DataFrame(data)
```
则可以使用 `dataframe.iloc` 来选择特定行或列的数据:
```
# 选择第一行
df.iloc[0]
# 选择第一列
df.iloc[:, 0]
# 选择第二行第三列的数据
df.iloc[1, 2]
# 选择第一行和第三行,第二列和第三列的数据
df.iloc[[0, 2], 1:3]
```
需要注意的是,`dataframe.iloc` 中的 row_index 和 column_index 都是基于 0 开始的整数位置。同时,`dataframe.iloc` 是基于位置选择数据的方法,不支持使用标签进行选择。如果需要使用标签进行选择,可以使用 `dataframe.loc` 方法。