Pandas 设置索引:使用 set_index() 方法
在 Pandas 中,可以使用 set_index() 方法将某一列设置为索引。下面是一个示例:
import pandas as pd
# 创建一个 DataFrame
data = {'A': [1, 2, 3, 4, 5],
'B': ['a', 'b', 'c', 'd', 'e'],
'C': [10, 20, 30, 40, 50]}
df = pd.DataFrame(data)
# 将列'A'设置为索引
df.set_index('A', inplace=True)
print(df)
输出结果如下:
B C
A
1 a 10
2 b 20
3 c 30
4 d 40
5 e 50
在上面的示例中,我们使用 set_index() 方法将列'A'设置为索引,并使用 inplace=True 参数将修改应用到原始 DataFrame 上。
原文地址: http://www.cveoy.top/t/topic/dUwm 著作权归作者所有。请勿转载和采集!