分配一个类别,根据值的范围作为新列,python

Assign a category, according to range of the value as a new column, python

我有一段 R 代码,我正试图弄清楚如何在 Python pandas 中执行此操作。 它需要一个名为 INDUST_CODE 的列并 检查其值以根据值的范围将类别分配为新列。 请问我如何才能在python好吗?

  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)

您可以使用 pandas.cut 将其组织到与您的示例一致的容器中。

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]