我有一个数据框,其中有一列包含街道交叉口
| 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/