python-3.x - 根据熊猫中给定列的值保留行
问题描述
给定一个数据框,我想保留给定列值与给定字符串不匹配的行。
例如,如果列“En”与“x1”不匹配,我将保留这些行。我使用下面的代码来做到这一点。
df1 = df1.loc[df1['En'] != 'x1']
如果不是x1
仅,存在x1
并且x2
需要检查。换句话说,我将只保留 'En' 列与x1
or不匹配的行x2
。最有效的方法是什么。
我就是这样做的
df1 = df1.loc[df1['En'] != 'x1']
df1 = df1.loc[df1['En'] != 'x2']
解决方案
你在寻找这样的东西吗?
import pandas as pd
df1 = pd.DataFrame({'a' : ['one', 'one', 'two', 'three', 'two', 'one', 'six'],
'b' : ['x', 'y', 'z', 'x', 'y', 'x', 'z'],
'c' : [1,2,3,4,5,6,7]})
print(df1)
df2 = df1.loc[(df1['b'] != 'x') & (df1['b'] != 'y') ]
print (df2)
如果 df1 是:
a b c
0 one x 1
1 one y 2
2 two z 3
3 three x 4
4 two y 5
5 one x 6
6 six z 7
那么 df2 将是:
a b c
2 two z 3
6 six z 7
另一种方法是使用查询。
df2 = df1.query("b != 'x' & b != 'y'")
或者
df2 = df1.query("b != ['x','y']")
这也会给你同样的结果。
有关使用其中一些运算符的更多信息,请参阅https://pandas.pydata.org/pandas-docs/version/0.13.1/indexing.html
推荐阅读
- javascript - 是否有全局文档帧数?
- java - 如何在 Java Android 中停止程序 1 秒?
- javascript - `unknown` 用法上的 TypeScript 3.0 错误
- javascript - angularjs 从 ng-src 中删除 $scope.expression
- interactive-brokers - 您可以对盈透证券进行回测吗?
- git - 如何从现有项目在本地主机上设置裸 git 存储库?
- c++ - std::shared_ptr::unique(),复制和线程安全
- angular - ngIf 表达式在检查后发生了变化
- c# - 使用 Newtonsoft.Json 从 Steam 商店 API 获取数据
- java - 如何将地震条目索引的结果添加到新列表中?