【问题标题】:Mapping list of stings to 0 in Pandas Python在 Pandas Python 中将字符串列表映射到 0
【发布时间】:2019-08-29 01:35:27
【问题描述】:

我正在尝试使用 Open BigQuery 数据集研究酒精和药物对车祸的影响。我已经准备好我的数据集,并且正在进一步完善它。我想对 pandas 列中的字符串条目进行分类。

数据框有超过 11,000 个条目,每列大约有 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

【问题讨论】:

  • 为什么你需要一份你不想要的东西的清单?只需保留一个(较短的)您想要的东西的列表,然后将其他所有内容设置为 0。这不是要走的路吗?

标签: python string pandas mapping


【解决方案1】:

假设您的源列名为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)

【讨论】:

    【解决方案2】:

    所以,虽然上述方法工作正常。但是,他们并没有标记我以后要删除的所有类别。所以,我就用了这个方法,

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

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 1970-01-01
      • 2018-08-06
      • 2023-03-30
      • 2012-01-17
      • 2017-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多