我想替换strings
列中的位置词:如果它们要么单独出现,要么以多个形式出现,但与,
和space
连接
id strings
0 1 south
1 2 north
2 3 east
3 4 west
4 5 west, east, south
5 6 west, west
6 7 north, north
7 8 north, south
8 9 West Corporation global office
9 10 West-Riding
10 11 University of West Florida
11 12 Southwest
我的预期结果是这样的。请注意,如果它们是短语或单词的组成部分,那么我不需要替换它们
有可能吗?多谢各位
id strings
0 1 NaN
1 2 NaN
2 3 NaN
3 4 NaN
4 5 NaN
5 6 NaN
6 7 NaN
7 8 NaN
8 9 West Corporation global office
9 10 West-Riding
10 11 University of West Florida
11 12 Southwest
下面的代码可以工作,但我只是想知道是否有一些更简洁的方法
df['strings'].astype(str).replace('south', np.nan).replace('north', np.nan)\
.replace('west', np.nan).replace('east', np.nan).replace('west, east', np.nan)\
.replace('west, west', np.nan).replace('north, north', np.nan).replace('west, east', np.nan)\
.replace('north, south', np.nan)
首先使用^{} ,前向填充替换缺失值,测试所有匹配值是否由^{} 和^{} 匹配掩码,最后设置缺失值是否由^{} :
关于{}s、{}和{a5}的另一个想法:
使用正则表达式
Ex:
输出:
相关问题 更多 >
编程相关推荐