0

I have this code to replace ages from numeric data to categorical data. I'm trying to do it that way, but it's not working. Can anybody help me?

for df in treino_teste:
    df.loc[df['Age'] <= 13, 'Age'] = 0,
    df.loc[(df['Age'] > 13) & (df['Age'] <= 18), 'Age'] = 1,
    df.loc[(df['Age'] > 18) & (df['Age'] <= 25), 'Age'] = 2,
    df.loc[(df['Age'] > 25) & (df['Age'] <= 35), 'Age'] = 3,
    df.loc[(df['Age'] > 35) & (df['Age'] <= 60), 'Age'] = 4,
    df.loc[df['Age'] > 60, 'Age'] = 5

Error:

Error image

3
  • remove the trailing commas Commented Feb 28, 2021 at 15:48
  • 1
    also check out pd.cut() for something like this. Commented Feb 28, 2021 at 15:55
  • 1
    df['Age'] = pd.cut(df['Age'], [0, 13, 18, 25, 35, 60,130], labels=[0,1,2,3,4,5]),refer pandas cut Commented Feb 28, 2021 at 16:02

2 Answers 2

1
  • there is capability for categorising continuous data
  • for purpose of example I've assign the bin to a new column. I could have assigned it back to Age
  • for ease of reading results I have sorted, this is not needed
df = pd.DataFrame({"Age":np.random.randint(1,65,10)}).sort_values(["Age"])

bins = [0,13,18,25,35,60,100]
df.assign(AgeB=pd.cut(df.Age, bins=bins, labels=[i for i,v in enumerate(bins[:-1])]))

Age AgeB
5 12 0
3 13 0
8 18 1
7 25 2
9 25 2
1 27 3
2 30 3
4 57 4
0 59 4
6 64 5
Sign up to request clarification or add additional context in comments.

Comments

1

You can use numpy.digitize()

bins = [0,13,18,25,35,60,100]
df['AgeC'] =numpy.digitize(df['Age'],bins)

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.