在Python中将sting列表映射到0

2024-05-26 21:54:04 发布

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

我试图用一个开放的BigQuery数据集来研究酒精和毒品在车祸中的作用。我已经准备好了我的数据集,正在进一步完善它。我想对pandas列中的字符串条目进行分类

数据框有11000多个条目,每列中大约有44个唯一值。不过,我只想把“酒精参与”和“毒品(非法)”的条目分别归类为1和。我要将任何其他条目映射到0

我已经创建了一个列表,其中列出了我不关心并希望删除的所有条目,它们位于一个列表中,如下所示:

list_ign  = ['Backing Unsafely',
   'Turning Improperly', 'Other Vehicular',
   'Driver Inattention/Distraction', 'Following Too Closely',
   'Oversized Vehicle', 'Driver Inexperience', 'Brakes Defective',
   'View Obstructed/Limited', 'Passing or Lane Usage Improper',
   'Unsafe Lane Changing', 'Failure to Yield Right-of-Way',
   'Fatigued/Drowsy', 'Prescription Medication',
   'Failure to Keep Right', 'Pavement Slippery', 'Lost Consciousness',
   'Cell Phone (hands-free)', 'Outside Car Distraction',
   'Traffic Control Disregarded', 'Fell Asleep',
   'Passenger Distraction', 'Physical Disability', 'Illness', 'Glare',
   'Other Electronic Device', 'Obstruction/Debris', 'Unsafe Speed',
   'Aggressive Driving/Road Rage',
   'Pedestrian/Bicyclist/Other Pedestrian Error/Confusion',
   'Reaction to Other Uninvolved Vehicle', 'Steering Failure',
   'Traffic Control Device Improper/Non-Working',
   'Tire Failure/Inadequate', 'Animals Action',
   'Driverless/Runaway Vehicle']

我该怎么做才能将“酒精参与”和“毒品(非法)”分别映射为1和,并将列表中的所有内容设置为0


Tags: to数据right列表failuredriver条目other
2条回答

所以,尽管上述方法很有效。但是,它们并没有标记我以后要删除的所有类别。所以,我用这个方法

for word in list_ign:
    df = df.replace(str(word), 'Replace')

假设您的源列名为Crime

import numpy as np

df['Illegal'] = np.where(df['Crime'].isin(['Alcohol Involvement', 'Drugs']), 1, 0)

或者

df['Crime'] = df['Crime'].isin(['Alcohol Involvement', 'Drugs']).astype(int)

相关问题 更多 >

    热门问题