如何从 Python Pandas 中的列名获取列索引?
要从PythonPandas中的列名获取列索引,我们可以使用get_loc()方法。
步骤-
创建二维、大小可变、潜在异构的表格数据df。
打印输入数据帧df。
使用df.columns查找DataFrame的列。
打印步骤3中的列。
初始化变量column_name。
获取位置,即column_name的索引。
打印column_name的索引。
示例-
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
print"Input DataFrame 1 is:\n", df
columns = df.columns
print"给定DataFrame中的列: ", columns
column_name = "z"
column_index = columns.get_loc(column_name)
print"列的索引 ", column_name, " is: ", column_index
column_name = "x"
column_index = columns.get_loc(column_name)
print"列的索引 ", column_name, " is: ", column_index
column_name = "y"
column_index = columns.get_loc(column_name)
print"列的索引 ", column_name, " is: ", column_index输出结果Input DataFrame 1 is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 给定DataFrame中的列: Index(['x', 'y', 'z'], dtype='object') 列的索引 z is: 2 列的索引 x is: 0 列的索引 y is: 1
热门推荐
10 中考祝福语给同学简短
11 交接同事退休祝福语简短
12 金婚祝福语大全简短唯美
13 爸爸寿宴仪式祝福语简短
14 集体生日祝福语简短的
15 高考成绩高分祝福语简短
16 祝贺母校祝福语简短英语
17 生气蛋糕祝福语大全简短
18 小学同学简短祝福语