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

Time:12-04

I'm trying to apply a simple function on a pd.DataFrame but I need the index of each element while applying.

Consider this DataFrame:

CLM_1 CLM_1
A foo bar
B bar foo
C bar foo

and I want a pd.Series as result like so:

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

My approach: I used df.apply(lambda row: row.index, axis=1) which obviously didn't work.

CodePudding user response:

Use to_series() on the index:

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

If you want to use the index in a function, you can assign it as a column and then apply whatever function you need:

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

  • Related