Python检索数据框的行索引

时间:2018-11-05 08:00:20

标签: python pandas dataframe

请问如何在DataFrame中检索行的索引? 具体来说,我能够从df.loc检索行的索引。

idx = data.loc[data.name == "Smith"].index

我甚至可以使用data.index这样从df.loc中检索行索引:

idx = data.loc[data.index == 5].index

但是,我不能直接从行本身(即从row.index而不是df.loc []。index)检索索引。我尝试使用以下代码:

idx = data.iloc[5].index

此代码的结果是列名。

要提供上下文,我需要检索特定行(而不是df.loc中的行)的索引的原因是对每行使用df.apply。 我计划使用df.apply将代码应用于每行,并从紧接其上方的行中复制数据。

def retrieve_gender (row):
    # This is a panel data, whose only data in 2000 is already keyed in. Time-invariant data in later years are the same as those in 2000.
    if row["Year"] == 2000:
        pass
    elif row["Year"] == 2001: # To avoid complexity, let's use only year 2001 as example.
        idx = row.index # This is wrong code.
        row["Gender"] = row.iloc[idx-1]["Gender"]
    return row["Gender"]


data["Gender"] = data.apply(retrieve_gender, axis=1)

2 个答案:

答案 0 :(得分:0)

使用Pandas,您可以像这样遍历数据框:

for index in range(len(df)): 
    if df.loc[index,'year'] == "2001":
        df.loc[index,'Gender'] = df.loc[index-1 ,'Gender']

答案 1 :(得分:0)

angular-cli.json给出按列标签索引的系列

apply的问题是idx = data.iloc[5].index将行转换为由列标签索引的data.iloc[5]对象

实际上,您要的内容通过pd.DataFrame.apply 是不可能的,因为为pd.Series函数提供功能的系列不包含任何索引标识符。

改为使用矢量化逻辑

对于Pandas,逐行逻辑效率低下,不建议使用;它涉及一个Python级的循环。请改用按列逻辑。退后一步,您似乎希望实现2条规则:

  1. 如果retrieve_gender不是2001,请保持Year不变。
  2. 如果Gender是2001,请使用上一行的Year

Gender + np.where

对于上述逻辑,可以将np.wherepd.Series.shift结合使用:

shift

data['Gender'] = np.where(data['Year'] == 2001, data['Gender'].shift(), data['Gender']) + mask

或者,您可以使用mask + shift

shift