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")
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
"""