pandas如何设置现有列为索引
时间: 2023-10-13 16:17:36 浏览: 34
可以使用df.set_index方法将一个或多个现有列设置为索引,例如:
```
df.set_index('col_name') # 将'col_name'列作为索引
df.set_index(['col1', 'col2']) # 将'col1'和'col2'列作为多级索引
```
注意,在上述代码中,df表示pandas的DataFrame对象,'col_name'、'col1'和'col2'表示DataFrame中的列名。
相关问题
pandas设置某一列为索引
您可以使用 Pandas 中的 `set_index()` 方法来设置某一列为索引。例如,如果您的数据框叫做 `df`,您想要将名为 `column_name` 的列设置为索引,您可以使用以下代码:
```
df.set_index('column_name', inplace=True)
```
其中,`inplace=True` 表示您想要在原始数据框上进行修改,而不是创建一个新的数据框。
pandas设置多列索引
在 Pandas 中,可以使用 `set_index` 方法来设置多列索引。具体的代码示例如下:
```
import pandas as pd
# 创建一个简单的 DataFrame
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C': [1, 2, 3, 4, 5, 6, 7, 8],
'D': [10, 20, 30, 40, 50, 60, 70, 80]})
# 设置多列索引
df = df.set_index(['A', 'B'])
# 显示 DataFrame
print(df)
```
输出结果:
```
C D
A B
foo one 1 10
bar one 2 20
foo two 3 30
bar three 4 40
foo two 5 50
bar two 6 60
foo one 7 70
foo three 8 80
```
在上面的代码中,我们使用了 `set_index` 方法来将列 `A` 和列 `B` 设置为 DataFrame 的多列索引。