在 Pandas 中显示列为 False 的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45880474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display rows where a column is False in pandas
提问by SPy
I have a dataframe with one column(dtype=bool) contains True
/False
values, I want to filter the records if bool column == False
我有一个数据框,其中一列(dtype=bool)包含True
/False
值,如果 bool column == False,我想过滤记录
Below script gives error, please help.
下面的脚本给出了错误,请帮忙。
if mFile['CCK'].str.contains(['False']):
print(mFile.loc[mFile['CCK'] == False])
Error in
错误
if mFile['CCK'].str.contains(['False']
回答by con--
You don't need to convert the value to a string (str.contains
) because it's already a boolean. In fact, since it's a boolean, if you want to keep only the true values, all you need is:
您不需要将该值转换为字符串 ( str.contains
),因为它已经是一个布尔值。事实上,由于它是一个布尔值,如果您只想保留真实值,您只需要:
mFile[mFile["CCK"]]
Assuming mFile is a dataframe and CCK only contains True and False values
假设 mFile 是一个数据帧并且 CCK 只包含 True 和 False 值
Edit: If you want false values use:
编辑:如果你想要假值使用:
mFile[~mFile["CCK"]]
回答by cs95
To display only if a record is False
, you'll need to invert your condition:
要仅在记录为 时显示False
,您需要反转条件:
mFile[~mFile['CCK']])
MVCE:
MVCE:
Original:
原来的:
In [1273]: df
Out[1273]:
A B
0 False 8
1 True 98
2 True 97
3 False 106
4 False 50
5 False 80
6 False 80
7 True 72
8 False 117
9 False 29
Using boolean indexing
:
使用boolean indexing
:
In [1271]: df[~df.A].B
Out[1271]:
0 8
3 106
4 50
5 80
6 80
8 117
9 29
Name: B, dtype: int64
You could also use pd.Series.mask
:
您还可以使用pd.Series.mask
:
In [1272]: df.B.mask(df.A).dropna()
Out[1272]:
0 8.0
3 106.0
4 50.0
5 80.0
6 80.0
8 117.0
9 29.0
Name: B, dtype: float64
If your data has string entries, you'd need pd.Series.str.contains
:
如果您的数据有字符串条目,您需要pd.Series.str.contains
:
In [1278]: df[df.A.astype(str).str.contains('False')]
Out[1278]:
A B
0 False 8
3 False 106
4 False 50
5 False 80
6 False 80
8 False 117
9 False 29
For your case, it'd be
对于你的情况,它会是
mFile[mFile['CCK'].astype(str).str.contains('False') ]
To check if False-y
values exist, just get the mask and call pd.Series.any()
:
要检查False-y
值是否存在,只需获取掩码并调用pd.Series.any()
:
mFile['CCK'].astype(str).str.contains('False').any()
回答by J?rn Hees
how about:
怎么样:
if False in mFile['CCK']:
print(mFile[~mFile['CCK']])
you can use ~
as above or mFile['CCK'] == False
, which might be a bit more readable to others...
您可以使用~
如上或mFile['CCK'] == False
,这可能对其他人更具可读性...