3

Working with dataframe df:

Count
1
2
3
4
5

Want to add second column, that categorizes everything above 3 as '4+' - needed output:

Count | Category
1        1
2        2
3        3
4        4+
5        4+

This is my code:

df['Category'] = df['Count']
df = df.loc[df['Count'] > 3, 'Category'] = '4+'

And I get this error:

AttributeError: 'str' object has no attribute 'loc'
1
  • FYI - you can also use df['Category'] = np.where(df['Count'] < 4, df['Count'], '4+') Commented Sep 20, 2017 at 17:42

2 Answers 2

6

Just go with

df['Category'] = df['Count']
df.loc[df['Count'] > 3, 'Category'] = '4+'
Sign up to request clarification or add additional context in comments.

6 Comments

thank you - do you mind explainin, what I did wrong?
I just tried without the "df=" and I get the same error
Why wouldn't I use the df=?
You are already assigning using loc when you do df.loc[df['Count'] > 3, 'Category'] = '4+'. When you add df = ...., you are trying to assign twice in the same statement, which obviously wouldn't work
Is this answer actually working for you @jeangelj? I tried it and got Error ValueError: invalid literal for int() with base 10: '4+'
|
1

You can try out with:

import pandas as pd
df = pd.DataFrame({"Count": [1,2,3,4,5]})
df["Category"] = df["Count"].apply(str)
df["Category"][df['Count'] > 3] = "4+"

Output would be:

>>> df
   Count Category
0      1        1
1      2        2
2      3        3
3      4       4+
4      5       4+

4 Comments

It throws SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
Did you try the only the example I stated or you used your own dataframe? If you dataframe has numbers this should work.
Please go through this link to understand settingwithcopy warning and why should loc be used. stackoverflow.com/questions/20625582/…
Well, that's strange. I tried under Python 2.7 and 3.3 on pythonanywhere.com and got no warnings from my option.

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.