python pandas dataframe切片
时间: 2023-11-19 21:57:46 浏览: 109
以下是Python Pandas DataFrame切片的例子:
```python
import pandas as pd
# 创建一个DataFrame
data = {'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eric'],
'age': [25, 32, 18, 47, 33],
'country': ['US', 'Canada', 'UK', 'US', 'Canada']}
df = pd.DataFrame(data)
# 切片操作
# 选取前三行
df_slice = df[:3]
print(df_slice)
# 选取第二列
df_slice = df.iloc[:, 1]
print(df_slice)
# 选取第二列和第三列
df_slice = df.iloc[:, 1:3]
print(df_slice)
# 选取第一行和第三行
df_slice = df.iloc[[0, 2], :]
print(df_slice)
```
输出结果为:
```
name age country
0 Alice 25 US
1 Bob 32 Canada
2 Charlie 18 UK
age
0 25
1 32
2 18
3 47
4 33
age country
0 25 US
1 32 Canada
2 18 UK
3 47 US
4 33 Canada
name age country
0 Alice 25 US
2 Charlie 18 UK
```
阅读全文