根据值的范围将类别指定为一个新列python

2024-10-03 02:31:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段R代码,我正试图弄清楚如何在Python中实现它。 它需要一个名为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)

Tags: 代码indexservicetablecodeupdate类别full
1条回答
网友
1楼 · 发布于 2024-10-03 02:31:49

您可以使用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]

相关问题 更多 >