pandas中如何将某一列设置为索引
在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/iYyS 著作权归作者所有。请勿转载和采集!