【发布时间】:2020-11-10 06:40:58
【问题描述】:
给定一个玩具数据集如下:
id room_type company_name
0 1 office ABC ltd
1 2 office retail
2 3 office xyz ltd
3 4 retail retail
4 5 parking toy store
5 6 hall NaN
如果room_type 或company 列包含retail, parking or hall,则比较两列,如果它们不相同,则返回一个带有字符串Invalid company name or room type 的新列check。
我想使用如下代码,因为还有很多其他列要检查:
a = np.where(df['room_type'].str.contains('retail|parking|hall', na = False), 'Invalid company name or room type', None)
# b = np.where(df.area.str.contains('^\d+$', na = True), None,
# 'area is not a numbers')
f = (lambda x: ';'.join(y for y in x if pd.notna(y))
if any(pd.notna(np.array(x))) else np.nan )
df['check'] = [f(x) for x in zip(a)]
预期的结果是这样的:
id room_type company_name check
0 1 office ABC ltd NaN
1 2 office retail Invalid company name or room type
2 3 office xyz ltd NaN
3 4 retail retail NaN
4 5 parking toy store Invalid company name or room type
5 6 hall NaN Invalid company name or room type
如何修改条件a 代码?提前感谢您的帮助。
【问题讨论】:
标签: python-3.x pandas string dataframe