【问题标题】:How to correctly use map and use np.where to replace values in a column如何正确使用 map 并使用 np.where 替换列中的值
【发布时间】:2020-11-14 02:22:06
【问题描述】:

这是我的数据框 df.city 的城市列

array(['la', 'hollywood', 'pasadena', 'los angeles', 'new york',
       'studio city', 'venice', 'santa monica', 'mar vista',
       'beverly hills', 'w. hollywood', 'encino', 'st. boyle hts .',
       'westlake village', 'westwood', 'west la', 'chinatown',
       'monterey park', 'rancho park', 'redondo beach', 'long beach',
       'marina del rey', 'culver city', 'burbank', 'century city',
       'malibu', 'seal beach', 'northridge', 'st. hermosa beach'],
      dtype=object)

我希望将包含['la','hollywood'] 的字符串转换为'los angeles'。如何做到这一点,我为此使用了np.where(condition,x,y),但它的第三个参数(y)让我失望了。

为了替换其他城市,我制作了这本词典

cities={'studio city':'los angeles', 'santa monika':'los angeles', 'mar vista':'los angeles', 'beverly hills':'los angeles', 'encino':'los angeles', 'st. boyle hts .':'los angeles', 'westwood':'los angeles', 'chinatown':'los angeles', 'moterey park':'los angeles', 'rancho park':'los angeles', 'redondo beach':'los angeles', 'century city':'los angeles', 'marina del rey':'los angeles', 'malibu':'los angeles', 'seal beach':'los angeles', 'northridge':'los angeles','st. hermosa beach':'los angeles'}

当我使用 df.city.map(cities) 时,它会映射字典中存在的那些,并用 NaN 替换其他的,例如“los angeles”。 我该如何清理我的数据框列的这一列?

【问题讨论】:

  • 使用df['city'].replace(cities)

标签: pandas numpy mapping data-cleaning


【解决方案1】:

你可以像这样使用np.where

df['city'] = np.where((df['city'].str.contains('la'))| (df['city'].str.contains('hollywood')), 'los angeles', df['city'])

第三个参数只是原始列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 2019-06-24
    • 2021-07-16
    • 2020-01-12
    • 2023-03-25
    • 2023-03-25
    相关资源
    最近更新 更多