【问题标题】:Multiple String cleaning in pandas熊猫中的多个字符串清理
【发布时间】:2019-07-24 13:34:45
【问题描述】:

我正在清理包含如下位置的数据框中的列:

New York City
New York, NY
New York USA
Las Vegas, Nevada
Las Vegas, NV, USA
Las Vegas North, America

如何清理字符串,使其只返回城市,即:

New York
New York
New York
Las Vegas
Las Vegas
Las Vegas

我尝试了df.replace({'Location' : { 'New York.*' : 'New York', 'Las Vegas.*':'Las Vegas'}}) 和其他几个选项,但无法正常工作。

非常感谢任何帮助

【问题讨论】:

  • 您只与美国城市打交道吗?试试this regex 喜欢df['Location'] = df['Location'].str.replace(reg, r'\1')
  • 不,我正在使用一系列位置,而不仅仅是在美国

标签: regex string pandas data-cleaning


【解决方案1】:

这似乎有效

df['Location'] = df['Location'].str.replace(r'(^.*New York.*$)', 'New York')
df['Location'] = df['Location'].str.replace(r'(^.*Las Vegas.*$)', 'Las Vegas')

取自Replace whole string if it contains substring in pandas

【讨论】:

    猜你喜欢
    • 2023-01-11
    • 2018-11-23
    • 1970-01-01
    • 2019-07-26
    • 2021-04-01
    • 2019-04-12
    • 2021-09-21
    • 1970-01-01
    • 2020-11-17
    相关资源
    最近更新 更多