pandas 解决方式:值错误:序列的真值不明确,请使用.empty、.bool()、.item()、.any()或.all()

ujv3wf0j  于 2022-11-20  发布在  其他
关注(0)|答案(2)|浏览(251)

我正在创建一个函数对数据进行分类,但收到此错误:值错误:Series的真值不明确。请使用.empty、.bool()、.item()、.any()或.all()。

import pandas as pd

df=pd.read_csv(r'C:\Users\gabri\Downloads\credit_scoring_eng.csv')

def economic_class(valor):
    if valor<=16000:
        return 'economic_class'
    elif valor<=24000:
        return 'executive_class'
    elif valor<=32000:
        return 'first_class'
    else:
        return 'five_star_class'
df['class'] = df['total_income'].apply(economic_class)

下面是完整的错误:

Cell In [172], line 3
      1 # Criar coluna com categorias
      2 print(df['total_income'])
----> 3 df['class'] = df['total_income'].apply(economic_class)

File c:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\series.py:4433, in Series.apply(self, func, convert_dtype, args, **kwargs)
   4323 def apply(
   4324     self,
   4325     func: AggFuncType,
   (...)
   4328     **kwargs,
   4329 ) -> DataFrame | Series:
   4330     """
   4331     Invoke function on values of Series.
   4332 
   (...)
   4431     dtype: float64
   4432     """
-> 4433     return SeriesApply(self, func, convert_dtype, args, kwargs).apply()

File c:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\apply.py:1082, in SeriesApply.apply(self)
   1078 if isinstance(self.f, str):
   1079     # if we are a string, try to dispatch
...
   1528         f"The truth value of a {type(self).__name__} is ambiguous. "
   1529         "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1530     )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我已经尝试了很多解决这个错误在互联网上,但没有工作;-;
我希望为 Dataframe 创建一个新列。

luaexgnf

luaexgnf1#

尝试以下方法。提供虚拟数据或数据样本(不是图像)也很有帮助。
如果没有提供数据,您可以调整以下示例,使其正常工作

import pandas as pd

data = {'Name':['Bob','Kyle','Kevin','Dave'],
        'Value':[1000,20000,40000,30000]}

df = pd.DataFrame(data)
display(df)

def economic_class(valor):
    if valor<=16000:
        valor = 'economic_class'
        
    elif valor<=24000:
        valor = 'executive_class'
        
    elif valor<=32000:
        valor = 'first_class'
        
    else:
        valor = 'five_star_class'
        
    return valor

df['class'] = df['Value'].apply(economic_class)
display(df)
mctunoxg

mctunoxg2#

你的函数是正确的。我想问题是apply。你能试试这个吗:

def economic_class(valor):
    if valor<=16000:
        return 'economic_class'
    elif valor<=24000:
        return 'executive_class'
    elif valor<=32000:
        return 'first_class'
    else:
        return 'five_star_class'
df['class'] = df['total_income'].apply(lambda x: economic_class(x))

相关问题