如何在使用 pandas 应用函数时获取应用元素的索引?

how to get the applying element's index while using pandas apply function?

我正在尝试在 pd.DataFrame 上应用一个简单的函数,但在应用时我需要每个元素的索引。

考虑这个 DataFrame:

CLM_1 CLM_1
A foo bar
B bar foo
C bar foo

我想要一个 pd.Series 这样的结果:

A    'A'
B    'B'
C    'D'
Length: 3, dtype: object

我的做法: 我使用了 df.apply(lambda row: row.index, axis=1) 显然没有用。

在索引上使用to_series()

>>> df.index.to_series()
A    A
B    B
C    C
dtype: object

如果您想在函数中使用索引,您可以将其分配为列,然后应用您需要的任何函数:

df["index"] = df.index
>>> df.apply(lambda row: row["CLM_1"]+row["index"], axis=1)
A    fooA
B    barB
C    barC
dtype: object

我使用了应用行的 name 属性,效果很好!无需向我的 DataFrame 添加更多列。
df.apply(lambda row: row.name, axis=1)