。替换为python中的字符串和int

2024-05-18 13:56:43 发布

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

df['sales'].replace(['sales', 'accounting', 'hr', 'technical', 'support', 'management',
        'IT', 'product_mng', 'marketing', 'RandD'], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], inplace = True)

这是我正在使用的代码,df是一个数据帧,其中的一列是sales

我得到以下错误:

enter image description here

有没有其他的函数可以用来执行这个替换操作,或者我在这里遗漏了什么

谢谢


Tags: truesupportdfhritproductmanagementmarketing
2条回答

您可以使用列表理解:

df['sales'] = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] if i in ['sales', 'accounting', 'hr', 'technical', 'support', 'management',
    'IT', 'product_mng', 'marketing', 'RandD'] else i for i in df["sales"]]

我真的不知道你想要完成什么,所以我给你两个选择:

df['sales'] = [ index for index, val in enumerate(['sales', 'accounting', 'hr', 'technical', 'support', 'management',
    'IT', 'product_mng', 'marketing', 'RandD'])]

或:

df['sales'] = [ index for index, val in enumerate(df['sales'])]

相关问题 更多 >

    热门问题