Reputation: 155
I have a piece of R code that i am trying to figure out how to do in Python pandas. It takes a column called INDUST_CODE and check its value to assign a category according to range of the value as a new column. May i ask how i can do something like that in python please?
industry_index <- full_table_update %>%
mutate(industry = case_when(
INDUST_CODE < 1000 ~ 'Military_service',
INDUST_CODE < 1500 & INDUST_CODE >= 1000 ~ 'Public_service',
INDUST_CODE < 2000 & INDUST_CODE >= 1500 ~ 'Private_sector',
INDUST_CODE >= 2000 ~ 'Others'
)) %>%
select(industry)
Upvotes: 1
Views: 1136
Reputation: 5746
You can use pandas.cut
to organise this into bins in line with your example.
df = pd.DataFrame([500, 1000, 1001, 1560, 1500, 2000, 2300, 7, 1499], columns=['INDUST_CODE'])
INDUST_CODE
0 500
1 1000
2 1001
3 1560
4 1500
5 2000
6 2300
7 7
8 1499
df['Categories'] = pd.cut(df['INDUST_CODE'], [0, 999, 1499, 1999, 100000], labels=['Military_service', 'Public_service', 'Private_sector', 'Others'])
INDUST_CODE Categories
0 500 Military_service
1 1000 Public_service
2 1001 Public_service
3 1560 Private_sector
4 1500 Private_sector
5 2000 Others
6 2300 Others
7 7 Military_service
8 1499 Public_service
Categories (4, object): [Military_service < Public_service < Private_sector < Others]
Upvotes: 2