【发布时间】:2019-04-08 13:49:57
【问题描述】:
请问如何在 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)
【问题讨论】: