This question already has answers here:
How to check whether a pandas DataFrame is empty?
                                
                                    (4个答案)
                                
                        
                                2年前关闭。
            
                    
给定一个数据框df,我将应用一些条件df[condition]并检索一个子集。我只想检查子集中是否有任何行-这可以告诉我条件是有效的。

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


检查过滤的数据框是否具有行的最佳方法是什么?这是一些无效的方法:


if df[df.Col1 == 1]:给出ValueError: The truth value of a DataFrame is ambiguous.
if df[df.Col1 == 1].any():还给出ValueError


我想我可以测试len。还有其他方法吗?

最佳答案

您可以使用df.empty

df_conditional = df.loc[df['column_name'] == some_value]
if not df_conditional.empty:
    ... # process dataframe results

关于python - 一种检查数据框是否有任何行的 Pandas 式方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45780130/

10-12 17:00
查看更多