0

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.

0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

yes it works but I'm applying a different function and I need the index at applying time. to be more specific, I'm counting the occurrence of each index in a string.
That wasn't your question. Why not just assign a new column as index and then use it? See the edit.
that's what I wanted. thank you. but isn't there any better ways to access the index while applying functions? in JS for example, while using Array.map & Array.foreach we have access to the value and it's index at the same time.(arr.map((item, index) => {...}))
No idea about JS. This is how I would do it in Python.
1

I used name attribute of the applying row and it worked just fine! no need to add more columns to my DataFrame.
df.apply(lambda row: row.name, axis=1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.