检查数据框是否有任何行的 pandas 式方法 [英] Pandaic way to check whether a dataframe has any rows
本文介绍了检查数据框是否有任何行的 pandas 式方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个数据框df
,我将应用一些条件df[condition]
并检索一个子集.我只想检查子集中是否有任何行-这可以告诉我条件是有效的.
Given a dataframe df
, I'd apply some condition df[condition]
and retrieve a subset. I just want to check if there are any rows in the subset - this would tell me the condition is a valid one.
In [551]: df
Out[551]:
Col1
0 1
1 2
2 3
3 4
4 5
5 3
6 1
7 2
8 3
我要检查的是这样的:
if df[condition] has rows:
do something
检查已过滤的数据框是否具有行的最佳方法是什么?这是一些无效的方法:
What is the best way to check whether a filtered dataframe has rows? Here's some methods that don't work:
-
if df[df.Col1 == 1]:
给出ValueError: The truth value of a DataFrame is ambiguous.
if df[df.Col1 == 1].any():
还给出了ValueError
我想我可以测试len
.还有其他方法吗?
I suppose I can test the len
. Are there other ways?
推荐答案
您可以使用df.empty
:
df_conditional = df.loc[df['column_name'] == some_value]
if not df_conditional.empty:
... # process dataframe results
这篇关于检查数据框是否有任何行的 pandas 式方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文