我有以下代码行:
# slice off the last 4 chars in name wherever its code contains the substring '-CUT'
df['name'] = np.where(df['code'].str.contains('-CUT'),
df['name'].str[:-4], df['name'])
但是,这似乎无法正常工作。它将最后四个字符切成正确的列,但也将其用于代码为None / empty(几乎所有实例)的行。
我在使用np.where的方式上有明显的错误吗?
答案 0 :(得分:4)
您可以将regex=False
和na=False
指定为pd.Series.str.contains
的参数,以便仅更新满足条件的行:
df['name'] = np.where(df['code'].str.contains('-CUT', regex=False, na=False),
df['name'].str[:-4], df['name'])
regex=False
对于此标准不是严格必需的,但它可以提高性能。 na=False
确保无法通过str
方法处理的任何类型都返回False
。
或者,您可以使用pd.DataFrame.loc
。这似乎比指定“不变”系列作为np.where
的最终参数更自然:
mask = df['code'].str.contains('-CUT', regex=False, na=False)
df.loc[mask, 'name'] = df['name'].str[:-4]