python - 从数据框单元格中的字符串中删除单词/字符?

标签 python pandas

我有一个数据框,其中有一列包含街道交叉口

|          Locations           |
--------------------------------
|W Madison Ave & S Randall Blvd|
|N Clemson St & E Tower Ave    |
|E Thompson St & S Garfield Ln |

我想删除方向字符(N、S、E、W)以及街道的后缀(Blvd、St、Ave 等...),以便我的输出看起来像这样

|     Locations     |
---------------------
|Madison & Randall  |
|Clemson & Tower    |
|Thompson & Garfield|

我不能执行 str.replace(),因为它会从我需要保留的单词中删除字符。我尝试使用 lstrip()rstrip() 但这不能修复我想从字符串中间删除的字符。

我还尝试使用 Series.apply()

banned = ['N', 'S', 'E', 'W', 'Ave', 'Blvd', 'St', 'Ln']
df["Locations"].apply(lambda x: [item for item in x if item not in banned])

但这实际上执行了一个 str.replace() 并将所有内容放在数据框中的列表中。

最佳答案

你很接近 - 你可以先拆分值,然后 join:

f = lambda x: ' '.join([item for item in x.split() if item not in banned])
df["Locations"] = df["Locations"].apply(f)

或者列表理解:

df["Locations"] = [' '.join([item for item in x.split() 
                  if item not in banned]) 
                  for x in df["Locations"]]


print (df)
             Locations
0    Madison & Randall
1      Clemson & Tower
2  Thompson & Garfield

关于python - 从数据框单元格中的字符串中删除单词/字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51879018/

相关文章:

Python click,你能把 -h 作为别名吗

python - 在数据框中找到最后一个值和相应的列名

python - 仅打印与工作日相对应的上周日期

python - 如何将 .txt 文件中的长文本插入到 DataFrame

python - 这个选角任务是如何进行的?

python - 使用 Python 中 ma numpy 中的 fiil_value 将屏蔽值 (--) 替换为 Null 或 None 值

python - Pandas DataFrame 没有完整的数据,而是使用三个点

python - Access 插入值

python - 从 pandas 数据框中消除只有一个值的列的最佳方法

python - Pandas:保留排除某些值的字典中的数据帧