[英]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.