【问题标题】:Create self-function and get ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()创建自函数并得到ValueError:DataFrame的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
【发布时间】:2021-07-18 02:00:48
【问题描述】:

我创建如下函数:

import pandas as pd
DATAPATH = "path/"

df_orig = pd.read_csv(DATAPATH + "file.csv" , dtype=str, sep = "|")

def test(df = None, df2 = None):
    if df == None:
        pass
    elif not isinstance(df, pd.DataFrame):
        df_in = pd.read_csv(DATAPATH + df + ".csv", dtype=str, sep = "|")
        print(f'============ Number of obs. in {df} ============\n{df_in.shape[0]:,}\n')
        print(f'============ First 10 Records of {df}.csv ============\n{df_in.head(10)}\n\n\n')
        print(f'============ Last 10 Records of {df}.csv ============\n{df_in.tail(10)}\n\n\n')
    else:
        df_in = df
        print(f'============ Number of obs. ============\n{df_in.shape[0]:,}\n')
        print(f'============ First 10 Records ============\n{df_in.head(10)}\n\n\n')
        print(f'============ Last 10 Records ============\n{df_in.tail(10)}\n\n\n')

    if df2 == None:
        pass
    elif not isinstance(df2 , pd.DataFrame):
        df_in2 = pd.read_csv(DATAPATH + df2 + ".csv", dtype=str, sep = "|")
        print(f'============ Number of obs. in {df2} ============\n{df_in2.shape[0]:,}\n')
        print(f'============ First 10 Records of {df2}.csv ============\n{df_in2.head(10)}\n\n\n')
        print(f'============ Last 10 Records of {df2}.csv ============\n{df_in2.tail(10)}\n\n\n')
    else:
        df_in2 = df2
        print(f'============ Number of obs. ============\n{df_in2.shape[0]:,}\n')
        print(f'============ First 10 Records ============\n{ddf_in2_in.head(10)}\n\n\n')
        print(f'============ Last 10 Records ============\n{df_in2.tail(10)}\n\n\n')


test(df = df_orig, df2 = None)

但是,我得到了错误:

Traceback (most recent call last):
  File "test.py", line 21, in <module>
    test(df = df_orig)
  File "test.py", line 7, in test
    if df == None:
  File "/mypath/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py", line 1443, in __nonzero__
    f"The truth value of a {type(self).__name__} is ambiguous. "
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

对此有何建议?
我对if df == None: 使用了错误的逻辑吗?

【问题讨论】:

    标签: python pandas function valueerror


    【解决方案1】:

    official 检查DataFrames是否为空的方式:

    
    if df.empty:
        # do something
    

    另一种方法是检查长度:

    if len(df) == 0:
        # do something
    

    编辑:cmets 让我相信您的操作顺序在这里是错误的。

    def test(df = None):
        if not isinstance(df, pd.DataFrame):
            pass # do whatever
        elif df.empty:
            pass # do whatever else
    

    None 没有长度,所以len() 会抛出错误,而如果 df 也是 Nonedf.empty 也会抛出错误。只需先检查 df 是否为 DatFrame,这将处理 None 值。

    【讨论】:

    • 即使我将not isinstance(df, pd.DataFrame) 更改为df.empty,仍然出现同样的错误。我想让if df == None: pass 离开那里,这样我就可以跳过这部分并做下一件事情,因为上面只是一个简单的例子。
    • 试试 len(df) == 0?
    • TypeError: object of type 'NoneType' has no len()
    • 我可能误解了您的评论,但您不应该将not isinstance 更改为df.empty,而是将df == none 更改为df.empty 或长度一。
    • 我相当肯定您的问题在于操作顺序。首先检查它是否是一个实例,编辑我的答案。
    猜你喜欢
    • 1970-01-01
    • 2021-07-31
    • 2021-11-28
    • 2021-08-31
    • 2016-12-01
    • 2019-01-24
    • 2021-08-06
    • 2020-05-27
    • 1970-01-01
    相关资源
    最近更新 更多