python - 熊猫数据框选择具有多列字符串条件的行
问题描述
我有一个类似的数据框:
df = pd.DataFrame([{'year':2017, 'text':'yes it is', 'label_one':'POSITIVE', 'label_two':'positive'},
{'year':2017, 'text':'it could be', 'label_one':'POSITIVE', 'label_two':'negative'},
{'year':2017, 'text':'it may be', 'label_one':'NEGATIVE', 'label_two':'positive'},
{'year':2018, 'text':'it has to be done', 'label_one':'POSITIVE', 'label_two':'positive'},
{'year':2018, 'text':'no', 'label_one':'NEGATIVE', 'label_two':'negative'},
{'year':2019, 'text':'you should be afraid of it', 'label_one':'POSITIVE', 'label_two':'negative'},
{'year':2019, 'text':'he is right', 'label_one':'POSITIVE', 'label_two':'positive'},
{'year':2020, 'text':'do not mind, I wil fix it', 'label_one':'NEGATIVE', 'label_two':'positive'},
{'year':2020, 'text':'that is a trap', 'label_one':'NEGATIVE', 'label_two':'negative'},
{'year':2021, 'text':'I am on my way', 'label_one':'POSITIVE', 'label_two':'positive'}])
我如何过滤它以便只有行label_one
和label_two
字符串值都是POSITIVE/positive
或NEGATIVE/negative
我尝试了以下方法,但它不起作用:
ptp = df.loc[(df['label_one'].str.startswith('P') and df['label_two'].str.startswith('p')) & (df['label_one'].str.startswith('N') and df['label_two'].str.startswith('n'))]
解决方案
关于什么
df[df['label_one'].str.lower() == df['label_two'].str.lower()]
假设label_one
且label_two
仅成立negative
, positive
,NEGATIVE
或POSITIVE
.
推荐阅读
- cobol - 在 COBOL 程序中出现重叠错误
- php - 无法在插件激活时创建表
- gstreamer - 对“QGst::Quick::VideoSurface::VideoSurface(QObject*)”的未定义引用
- javascript - 在 Google Apps 脚本中使用 google_services 状态页面 JSONP
- reactjs - clickOutside 钩子触发内部选择
- sql-server - 连接池如何与不同的 DbContext 一起工作
- sqlite - 有没有办法强制 SQLite 约束检查?
- onedrive - Power Automate 在某些步骤上识别文档库,但在其他步骤上不识别
- sql - 将 COUNT DISTINCT 与 FILTER 结合使用 - Spark SQL
- spring-retry - Spring重试异常表达式