Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: string indices must be integers when using .apply

I have this simple function:

def q1(x):
    if x['How likely are you to recommend us to a colleague?'] =='Extremely likely':
        return 10
    if x['How likely are you to recommend us to a colleague?']=='Not at all likely':
        return 0
    else:
        return x

The other values are from 1-9.
I’ve tried variations of the below, but I always get the same error

df.loc[:,'How likely are you to recommend us to a colleague?']=df['How likely are you to recommend us to a colleague?'].apply(q1)

I’ve also tried putting 10 and 0 in brackets (return "10" and return "0")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve tried creating a new column instead of replacing but the error is the same.

TypeError: string indices must be integers

>Solution :

Thy this:

def q1(x):
    if x == 'Extremely likely':
        return 10
    if x == 'Not at all likely':
        return 0
    return x

df['How likely are you to recommend us to a colleague?'] = df['How likely are you to recommend us to a colleague?'].apply(q1)

Example:

import pandas as pd

df = pd.DataFrame(
    {
        "How likely are you to recommend us to a colleague?": [
            "Extremely likely",
            "Extremely likely",
            "Not at all likely",
            "Not at all likely",
            "Somewhat likely",
        ]
    }
)
df['How likely are you to recommend us to a colleague?'] = df['How likely are you to recommend us to a colleague?'].apply(q1)
print(df)
# Prints:
"""
  How likely are you to recommend us to a colleague?
0                                                 10
1                                                 10
2                                                  0
3                                                  0
4                                    Somewhat likely
"""
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading