2

I am trying to pass an index from a df into my function so that my function can run through all of the rows of the df and provide the output which is a int in a new column called "TDNumber'.

Here is the code

 def createTdnumber(onedfindex):
    header.index    
    maski = header.index < onedfindex 
    finder = header[maski]
    tdnumber = max(finder.index)
    return tdnumber

df['TDNumber'] = df.index.apply(createTdnumber())

as indicated below The mask should receive a number such as 227 That 227 would be one of the numbers provided by df.index.apply to the function

 def createTdnumber(onedfindex):
    header.index    
    maski = header.index < 227 
    finder = header[maski]
    tdnumber = max(finder.index)
    return tdnumber

df['TDNumber'] = df.index.apply(createTdnumber())

This code generates the error 'Int64Index' object has no attribute 'apply'

For the 'Int64Index' how do I pass those numbers one at a time to my function?

header.index 

my output is

 Int64Index([0, 226, 470, 659, 863, 1108], dtype='int64')

from shx2 solution when I run

df.index.to_series()

The output is:

1          1
2          2
3          3
4          4
5          5
6          6
7          7
8          8
9          9
227      227
228      228
229      229
230      230
471      471
472      472
473      473
474      474
475      475
476      476

1 Answer 1

1

Index types don't have an apply method, but Series does.

To apply a function to your index, you can convert it to a series first, using its to_series method:

df['TDNumber'] = df.index.to_series().apply(createTdnumber)
Sign up to request clarification or add additional context in comments.

4 Comments

When I run the solution I get the error. "createTdnumber() takes exactly 1 argument (0 given) " I thought that with .apply I didn't need to put anything in the function parenthesis? Is there some other transformation that needs to occur? I posted some additional information in the question
maybe try: df['TDNumber'] = df.index.to_series().apply(lambda r: createTdnumber(r)) (@Erich)
or maybe just df['TDNumber'] = df.index.to_series().apply(createTdnumber) (@Erich)
race['Tdnumber'] = race.index.to_series().apply(lambda r: createTdnumber(r)) This worked @Paul H

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.