python - 检查数据框列是否已填充并按字符串搜索
问题描述
我有以下数据框:
import pandas as pd
import re
df = pd.DataFrame({'Column_01': ['Press', 'Temp', '', 'Strain gauge', 'Ultrassonic', ''],
'Column_02': ['five', 'two', 'five', 'five', 'three', 'three']})
我首先要检查“Column_01”是否已填充。如果填充了“Columns_01”或“Column_02”包含单词“one”、“two”、“three”。新列(分类器)将收到“传感器”。
为了识别“Column_02”字符串,我实现了以下代码:
df['Classifier'] = df.apply(lambda x: 'SENSOR'
if re.search(r'one|two|three', x['Column_02'])
else 'Nan', axis = 1)
此代码正在运行。它完美地找到了数据框行上的字符串。但是,我还需要检查“Column_01”是否已填充。我无法使用函数 notnull() 来解决问题。
我希望输出为:
Column_01 Column_02 Classifier
Press five SENSOR #current line of Column_01 completed
Temp two SENSOR #current line of Column_02 completed; string 'two'
five Nan
Strain gauge five SENSOR #current line of Column_01 completed
Ultrassonic three SENSOR #current line of Column_01 completed; string 'three'
three SENSOR #string 'three'
解决方案
通常你应该避免.apply()
(参考 https://stackoverflow.com/a/54432584/11610186)。
这应该可以解决问题:
import numpy as np
df["Classifier"]=np.where(df["Column_01"].fillna('').ne('')|df["Column_02"].str.contains("(one)|(two)|(three)"), "SENSOR", np.nan)
输出:
Column_01 Column_02 Classifier
0 Press five SENSOR
1 Temp two SENSOR
2 five nan
3 Strain gauge five SENSOR
4 Ultrassonic three SENSOR
5 three SENSOR
推荐阅读
- c# - C# selenium chromedriver 代理身份验证
- rx-java - RxJava - 即使调用 onNext() 如何阻止 PublishSubject 发布
- python - 如何使用正则表达式验证用户输入,并选择使用逗号输入多个条目?
- windows - 以 Azure AD 用户身份登录 Windows 10 服务
- katalon-studio - 在 Katalon 中捕获复制粘贴
- node.js - nodejs-express - 在主数据库上实现 Redis 缓存作为 mongodb
- sql - 如何计算 SQL 组中两个值的比率?
- r - 提取数据帧中最大单调递增/递减序列的元素
- javascript - 如何映射列表并在其中实现异步?
- database - 对于由多个不同服务共享的简单数据库(本质上只是一个键/值存储),最好的 AWS 服务是什么?