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'
jeangelj
  • 4,338
  • 16
  • 54
  • 98
  • FYI - you can also use `df['Category'] = np.where(df['Count'] < 4, df['Count'], '4+')` – Zero Sep 20 '17 at 17:42

2 Answers2

5

Just go with

df['Category'] = df['Count']
df.loc[df['Count'] > 3, 'Category'] = '4+'
Vaishali
  • 37,545
  • 5
  • 58
  • 86
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+
Cedric Zoppolo
  • 4,271
  • 6
  • 29
  • 59
  • It throws SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame – Vaishali Sep 20 '17 at 18:32
  • Did you try the only the example I stated or you used your own dataframe? If you dataframe has numbers this should work. – Cedric Zoppolo Sep 20 '17 at 18:52
  • Please go through this link to understand settingwithcopy warning and why should loc be used. https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas – Vaishali Sep 20 '17 at 18:59
  • Well, that's strange. I tried under Python 2.7 and 3.3 on [pythonanywhere.com](http://www.pythonanywhere.com) and got no warnings from my option. – Cedric Zoppolo Sep 20 '17 at 19:21