python的pandas取部分列
时间: 2023-10-17 13:19:23 浏览: 73
要选取DataFrame中的部分列,可以使用以下方法:
1. 使用列名选择单个列:
```python
df['column_name']
```
2. 使用列名列表选择多个列:
```python
df[['column_name_1', 'column_name_2', ...]]
```
3. 使用iloc方法选择列的位置:
```python
df.iloc[:, column_index]
df.iloc[:, [column_index_1, column_index_2, ...]]
```
其中,`:`表示选择所有行。
示例:
```python
import pandas as pd
data = {'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35],
'gender': ['F', 'M', 'M'],
'score': [80, 90, 85]}
df = pd.DataFrame(data)
# 选择单个列
print(df['name'])
# 选择多个列
print(df[['name', 'age']])
# 选择列的位置
print(df.iloc[:, 2])
```
输出:
```
0 Alice
1 Bob
2 Charlie
Name: name, dtype: object
name age
0 Alice 25
1 Bob 30
2 Charlie 35
0 F
1 M
2 M
Name: gender, dtype: object
```
阅读全文
相关推荐


















