Python Pandas - 如何通过传递行标签从 DataFrame 中选择行

要通过传递标签来选择行,请使用该loc()函数。提及要选择其行的索引。这是我们示例中的索引标签。我们有 x、y 和 z 作为索引标签,可用于选择带有loc().

创建一个数据帧 -

dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],index=['x', 'y', 'z'],columns=['a', 'b'])

现在,选择带有 loc 的行。我们已经通过了索引标签“z” -

dataFrame.loc['z']

示例

以下是代码 -

import pandas as pd

# 创建数据帧
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],index=['x', 'y', 'z'],columns=['a', 'b'])

# 数据框
print"DataFrame...\n",dataFrame

# 用 loc 选择行
print"\nSelect rows by passing label..."
print(dataFrame.loc['z'])
输出结果

这将产生以下输出 -

DataFrame...
     a     b
x   10   15
y   20   25
z   30   35

Select rows by passing label...
a   30
b   35
Name: z, dtype: int64