[英]How to ignore rows with a mask when using str.contains?
我有一个必须标准化的商店名称数据框。 例如麦当劳 1234 LA -> 麦当劳。 您可以在下面看到Popeyes和Wallmart已经标准化:
id store standard
0 1 McDonalds NaN
1 2 Lidl NaN
2 3 Lidl New York 123 NaN
3 4 KFC NaN
4 5 Slidling Shop NaN
5 6 Lidi Berlin NaN
6 7 Popeyes NY Popeyes
7 8 Wallmart LA 90210 Wallmart
8 9 Aldi NaN
9 10 London Lidl NaN
我使用str.contains
查找商店名称,并将标准化名称放入standard
列中。 在这里,我正在标准化Lidl商店:
df.loc[df.store.str.contains(r'\blidl\b', case=False), 'standard'] = 'Lidl'
print(df)
id store standard
0 1 McDonalds NaN
1 2 Lidl Lidl
2 3 Lidl New York 123 Lidl
3 4 KFC NaN
4 5 Slidling Shop NaN
5 6 Lidi Berlin NaN
6 7 Popeyes NY Popeyes
7 8 Wallmart LA 90210 Wallmart
8 9 Aldi NaN
9 10 London Lidl Lidl
然而,这里的问题是它在已经标准化的行(Popeyes 和 Wallmart)上搜索str.contains
。
如何仅在df['standard'] == NaN
行上运行str.contains
并忽略标准化行?
我尝试了一些非常非常混乱的东西,但它似乎不起作用。 我设置了一个掩码,然后在运行str.contains
之前使用它:
mask = df['standard'].isna()
df[mask].loc[df[mask].store.str.contains(aldi_regex,na=False), 'standard3'] = 'Aldi'
不起作用。 我还尝试了一些更凌乱的东西,但没有奏效:
df.loc[mask].loc[df.loc[mask].store.str.contains(aldi_regex,na=False), 'standard3'] = 'Aldi'
如何忽略标准化行? 无需求助于 for 循环。
我的示例数据框:
import pandas as pd
import re
df = pd.DataFrame({'id': pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10],dtype='int64',index=pd.RangeIndex(start=0, stop=10, step=1)), 'store': pd.Series(['McDonalds', 'Lidl', 'Lidl New York 123', 'KFC', 'Slidling Shop', 'Lidi Berlin', 'Popeyes NY', 'Wallmart LA 90210', 'Aldi', 'London Lidl'],dtype='object',index=pd.RangeIndex(start=0, stop=10, step=1)), 'standard': pd.Series([pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, 'Popeyes', 'Wallmart', pd.np.nan, pd.np.nan],dtype='object',index=pd.RangeIndex(start=0, stop=10, step=1))}, index=pd.RangeIndex(start=0, stop=10, step=1))
如何忽略标准化行? 无需求助于 for 循环。
通过过滤检查空值:
df.loc[df['standard'].isnull() & df.store.str.contains(r'\blidl\b', case=False), 'standard'] = 'Lidl'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.