基于最后一个字符修改Pandas DataFrame中stores变量的值
解决方法:按规则修改DataFrame的
stores列 针对需求,我们可以用两种高效的方法实现stores列的规则替换:
方法一:使用np.where多层条件判断
通过提取字符串最后一个字符进行条件匹配,逻辑直观清晰:
import pandas as pd import numpy as np data = { 'stores': ['Lexinton1','ROYAl2','Mall1','Mall2','Levis1','Levis2','Shark1','Shark','Lexinton'], 'quantity':[1,1,1,1,1,1,1,1,1] } df = pd.DataFrame(data, columns = ['stores', 'quantity']) # 按规则替换 df['stores'] = np.where( df['stores'].str[-1] == '1', 'open', np.where( df['stores'].str[-1] == '2', 'closed', df['stores'] ) ) print(df)
执行结果:
stores quantity 0 open 1 1 closed 1 2 open 1 3 closed 1 4 open 1 5 closed 1 6 open 1 7 Shark 1 8 Lexinton 1
方法二:使用正则表达式替换
利用正则匹配以1或2结尾的字符串,代码更简洁:
import pandas as pd import numpy as np data = { 'stores': ['Lexinton1','ROYAl2','Mall1','Mall2','Levis1','Levis2','Shark1','Shark','Lexinton'], 'quantity':[1,1,1,1,1,1,1,1,1] } df = pd.DataFrame(data, columns = ['stores', 'quantity']) # 替换以1结尾的字符串为open df['stores'] = df['stores'].replace(r'.*1$', 'open', regex=True) # 替换以2结尾的字符串为closed df['stores'] = df['stores'].replace(r'.*2$', 'closed', regex=True) print(df)
执行结果与方法一完全一致。
内容的提问来源于stack exchange,提问作者silent_hunter
相关产品推荐
相关产品推荐

