如何在 Python Pandas 中从列名称获取列索引?
若要在 Python Pandas 中从列名称获取列索引,我们可以使用 **get_loc()** 方法。
步骤 −
- 创建二维、长度可变、可能具有异构表格数据的 **df**。
- 打印输入 DataFrame **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"Columns in the given DataFrame: ", columns
column_name = "z"
column_index = columns.get_loc(column_name)
print"Index of the column ", column_name, " is: ", column_index
column_name = "x"
column_index = columns.get_loc(column_name)
print"Index of the column ", column_name, " is: ", column_index
column_name = "y"
column_index = columns.get_loc(column_name)
print"Index of the column ", 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 Columns in the given DataFrame: Index(['x', 'y', 'z'], dtype='object') Index of the column z is: 2 Index of the column x is: 0 Index of the column y is: 1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP