0

I created a defined function to add one month if the 'SR_NUMBER' is the same as the row above. I get the error message: 'float' object is not subscriptable. Here is the code I ran and the desired output:

dtypes: SR_Number: object

year_month_end: datetime64[ns]

Code attempt:

def SRfunction(row):
    if row['SR_NUMBER'] == row['SR_NUMBER'].shift(1):
        return row['year_month_end'] + MonthEnd(1)
    else:
        return row['year_month_end']

df['SR_NUMBER'] = df['SR_NUMBER'].apply(SRfunction)

Error message: 'float' object is not subscriptable

Original df:


df = pd.DataFrame({'SR_NUMBER':      ['2-15642332176', '3-22596843941', '3-22596843941', '3-22596843941', '3-22596843941'],
                   'year_month_end': ['2020-02-28', '2020-04-30', '2020-04-30', '2020-04-30', '2020-04-30']})

Desired output:

df = pd.DataFrame({'SR_NUMBER':       ['2-15642332176', '3-22596843941', '3-22596843941', '3-22596843941', '3-22596843941'],
                   'year_month_end':  ['2020-02-28', '2020-04-30', '2020-05-31', '2020-06-30', '2020-07-31']})
0

1 Answer 1

1

pd.DataFrame.apply is different from pd.Series.apply.

In this case row is not a row at all, but a single float value from the SR_NUMBER column.

If your applied function needs data that spans multiple columns, you need to use the DataFrame form of apply, but you are currently using the Series form.

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

1 Comment

THank you! Could you maybe elaborate further on how the full code would look if you were to fix it?

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.