Pandas: Accessing the index of a row in an apply function

Yao Yao on September 25, 2017

You CANNOT access each row’s index via lambda x: x.index in DataFrame.apply(axis=1) because apply treats each row as a numpy object, not a Series. However you can use lambda x: to access each row’s name, which happens to equal its index.

df.apply(axis=1, func=lambda x: func(x.index))  # Wrong!
df.apply(axis=1, func=lambda x: func(   # OK!

Another workaround is to use Note that this function does not preserve indices.

pd.Series( x: func(x)), index=df.index)

blog comments powered by Disqus