GVKun编程网logo

Pandas python ValueError:DataFrame 的真值不明确使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

1

最近很多小伙伴都在问PandaspythonValueError:DataFrame的真值不明确使用a.empty、a.bool()、a.item()、a.any()或a.all()这两个问题,那么本

最近很多小伙伴都在问Pandas python ValueError:DataFrame 的真值不明确使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展'bool?' 类型的值不能分配给类型为 'bool' 的变量,因为 'bool?'可以为空,而 'bool' 不是、Apply 和 Lambda 函数 - ValueError:系列的真值不明确使用 a.empty、a.bool()、a.item()、a.any() 或 a.all() 修复更好、Dataframe 的真值是不明确的使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()、DataFrame 的真值是不明确的在 Jupyter 中使用 a.empty、a.bool()、a.item()、a.any() 或 a.all() 错误等相关知识,下面开始了哦!

本文目录一览:

Pandas python ValueError:DataFrame 的真值不明确使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

Pandas python ValueError:DataFrame 的真值不明确使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

如何解决Pandas python ValueError:DataFrame 的真值不明确使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

我有 2 个数据框有问题 - 1 个包含公司中的官员 ID 和官员姓名:

officer_df = pd.DataFrame({''officerID'': [''01'',''02'',''03''],''Name'': [''Tom'',''Dick'',''Harry'']})

另一个包含官员ID和他们申请休假的休假日期:

 df_officer_leave = pd.DataFrame({''officerID'': [''01'',''01''],''leave start date'': [''2020-12-15'',''2020-12-31''],''leave end date'': [''2020-12-16'',''2021-01-02'']})

现在我想使用函数 leave_col_set 比较我的官员_df 中的官员 ID 并与 df_officer_leave 比较以返回 [休假开始日期,休假结束日期] 的列表,并将返回的列表作为新列添加到官员_df 基于官员 ID,但我一直有错误。

我不知所措,因此来堆栈溢出寻求指导。提前感谢好心人。

import pandas as pd
    officer_df = pd.DataFrame({''officerID'': [''01'',''Harry'']})
    
    
    df_officer_leave = pd.DataFrame({''officerID'': [''01'',''2021-01-02'']})
    
    df_officer_leave[''leave start date'']= pd.to_datetime(df_officer_leave[''leave start date''])
    df_officer_leave[''leave end date'']= pd.to_datetime(df_officer_leave[''leave end date''])
    
    def leave_col_set(x,df_officer_leave):
            return [*df_officer_leave[df_officer_leave[''officerID'']==x][[''leave start date'',''leave end date'']].values.tolist()]
        #leave logic
        
    
    
    officer_df["leaveDays"] = officer_df.officerID.apply(leave_col_set,args=(df_officer_leave))

解决方法

最后一行的正确语法是:

officer_df["leaveDays"] = officer_df.officerID.apply(leave_col_set,args=(df_officer_leave,))

有关详细信息,请参阅:Pass Dataframe to Apply function pandas as argument

话虽如此,我强烈考虑不将整个数据帧作为参数传递,特别是如果您只是提取信息。

在您的情况下,以下内容就足够了,因为您只需从函数内部访问 df_officer_leave

import pandas as pd

officer_df = pd.DataFrame({''officerID'': [''01'',''02'',''03''],''Name'': [''Tom'',''Dick'',''Harry'']})
df_officer_leave = pd.DataFrame({''officerID'': [''01'',''01''],''leave start date'': [''2020-12-15'',''2020-12-31''],''leave end date'': [''2020-12-16'',''2021-01-02'']})

df_officer_leave[''leave start date'']= pd.to_datetime(df_officer_leave[''leave start date''])
df_officer_leave[''leave end date'']= pd.to_datetime(df_officer_leave[''leave end date''])

def leave_col_set(x):
    return [*df_officer_leave[df_officer_leave[''officerID'']==x][[''leave start date'',''leave end date'']].values.tolist()]
    
officer_df[''leaveDays''] = officer_df.officerID.apply(leave_col_set)

'bool?' 类型的值不能分配给类型为 'bool' 的变量,因为 'bool?'可以为空,而 'bool' 不是

'bool?' 类型的值不能分配给类型为 'bool' 的变量,因为 'bool?'可以为空,而 'bool' 不是

如何解决''bool?'' 类型的值不能分配给类型为 ''bool'' 的变量,因为 ''bool?''可以为空,而 ''bool'' 不是?

这是我的完整代码...

import ''package:Flutter/cupertino.dart'';
import ''package:Flutter/material.dart'';
import ''package:get/get.dart'';

class DialogHelper{
  //show error dialog
 static void showErrorDialog({String title=''error'',String description=''Something went wrong''})
  {
    Get.dialog(
      Dialog(
        child: Padding(
          padding: const EdgeInsets.all(8.0),child: Column(
            mainAxisSize: MainAxisSize.min,children: [
              Text(title,style: Get.textTheme.headline4,),Text(description,style: Get.textTheme.headline6,ElevatedButton(onpressed: () {
                if (Get.isDialogopen) Get.back();
              },child: Text(''okay'')),],);

  }
}

我遇到了这个错误

19:25:错误:“bool”类型的值?不能分配给类型为 ''bool'' 的变量,因为 ''bool?''可以为空,而 ''bool'' 不是。 if (Get.isDialogopen) Get.back();

如果条件为 Get.isDialogopen,我在线上出错

解决方法

您收到该错误是因为 getter isDialogOpen 返回一个 Optional。这意味着返回值可以是 truefalsenull。但是,由于 if 条件只能与布尔值一起使用,因此 SDK 会告诉您如果 isDialogOpen 返回 null 会出现错误。

所以要解决这个问题,要么告诉编译器你确信你的 getter 永远不会返回空值,要么你必须给出一个默认值,以防从 .isDialogOpen 返回空值。我们分别这样做;

1-

  Get.isDialogOpen! \\ this means you are sure a null can''t be returned

2-

 Get.isDialogOpen ?? false \\ this means incase a null is returned use false   

注意:如果您使用数字 1,并且最终返回空值,您的代码将在运行时崩溃。为避免这种情况,您可以告诉编译器仅在 isDialogOpen 已初始化时调用它。即

Get?.isDialogOpen ?? false \\If isDialogOpen is not initialized,false will be used

Apply 和 Lambda 函数 - ValueError:系列的真值不明确使用 a.empty、a.bool()、a.item()、a.any() 或 a.all() 修复更好

Apply 和 Lambda 函数 - ValueError:系列的真值不明确使用 a.empty、a.bool()、a.item()、a.any() 或 a.all() 修复更好

如何解决Apply 和 Lambda 函数 - ValueError:系列的真值不明确使用 a.empty、a.bool()、a.item()、a.any() 或 a.all() 修复更好?

我正在尝试使用 Apply 和 Lambda 函数创建一个新列,如果“性别”为“女性”,则将“ID”值除以 219,如果“性别”为“男性”,则将其除以 393。首先,我尝试使用“性别”列,该列具有不起作用的分类变量。所以我创建了一个基于“性别”的二进制列,将 0 分配给“女性 1 到“男性”并使用该列,但没有用。

我仍然收到这样的值错误:

ValueError:系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

我的代码是

by_label_out_degree[normID] = by_label_out_degree.apply(lambda row: row[''ID'']/ 219 if row[''Gender2''] == 0 else row[''ID'']/ 393,axis=1)

我又要添加我的代码了!谢谢你的帮助!!

values = [
[42785,428855,''Energy'',''Female''],[43432,428686,''Trust'',''Male''],''Career'',''Personal'',428634,''Female'']
]
df: pd.DataFrame = pd.DataFrame(values,columns =[''ID'',''Target'',''Label'',''Gender''])
new_df = df.groupby([''Gender'',''Label'']).ID.count().reset_index()
new_df[''Gender2''] = new_df.Gender.map({''Female'':0,''Male'':1})
new_df[''normID''] = new_df.apply(lambda row: row[''ID'']/219 if row[''Gender2''] == 0 else row[''ID'']/393,axis = 1)

解决方法

修复

Gender 的使用效果很好

values = [
    [''Female'',''Access'',96],[''Female'',''Career'',165],[''Male'',236],''Energy'',445]
]
df: pd.DataFrame = pd.DataFrame(values,columns=[''Gender'',''Label'',''ID''])
df[''newcol''] = df.apply(lambda row: row[''ID''] / 219 if row[''Gender''] == ''Female'' else row[''ID''] / 393,axis=1)
print(df)

   Gender   Label   ID    newcol
0  Female  Access   96  0.438356
1  Female  Career  165  0.753425
2    Male  Access  236  0.600509
3    Male  Energy  445  1.132316

更好

使用numpy.where

import numpy as np
import pandas as pd

values = [[''Female'',445]]
df: pd.DataFrame = pd.DataFrame(values,''ID''])
df[''newcol''] = np.where(df[''Gender''] == ''Female'',df[''ID''] / 219,df[''ID''] / 393)
print(df)

Dataframe 的真值是不明确的使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

Dataframe 的真值是不明确的使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

如何解决Dataframe 的真值是不明确的使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

我尝试根据 my csv data 按照代码使用 seaborn site(此链接)由 seaborn 进行配对。

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

freq_data = pd.read_csv(''C:\\\\Users\\\\frequency.csv'')

freq = sns.load_dataset(freq_data)
df = sns.pairplot(iris,hue="condition",height=2.5)
plt.show()

结果显示了dataframe ambiguity的trackback

    Traceback (most recent call last):
  File "\\.vscode\\test.py",line 8,in <module>
    freq = sns.load_dataset(freq_data)
  File "\\site-packages\\seaborn\\utils.py",line 485,in load_dataset
    if name not in get_dataset_names():
  File "\\site-packages\\pandas\\core\\generic.py",line 1441,in __nonzero__   
    raise ValueError(
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty,a.bool(),a.item(),a.any() or a.all().

我已经检查了我的数据并在此处得到了结果

        condition    area  sphericity  aspect_ratio
0      20 kHz   0.249       0.287         1.376
1      20 kHz   0.954       0.721         1.421
2      20 kHz   0.118       0.260         1.409
3      20 kHz   0.540       0.552         1.526
4      20 kHz   0.448       0.465         1.160
..        ...     ...         ...           ...
310    30 kHz   6.056       0.955         2.029
311    30 kHz   4.115       1.097         1.398
312    30 kHz  11.055       1.816         1.838
313    30 kHz   4.360       1.183         1.162
314    30 kHz  10.596       0.940         1.715

[315 rows x 4 columns]
<class ''pandas.core.frame.DataFrame''>
RangeIndex: 315 entries,0 to 314
Data columns (total 4 columns):
 #   Column        Non-Null Count  Dtype  
---  ------        --------------  -----  
 0   condition     315 non-null    object 
 1   area          315 non-null    float64
 2   sphericity    315 non-null    float64
 3   aspect_ratio  315 non-null    float64
dtypes: float64(3),object(1)
memory usage: 10.0+ KB

我不知道我的数据框会发生什么:( 请建议我解决这些问题

谢谢大家

解决方法

seaborn.load_dataset() 的第一个参数是数据集的名称(https://github.com/mwaskom/seaborn-data 上的{name}.csv)而不是 pandas.DataFrame 对象。 seaborn.load_dataset()的返回值就是pandas.DataFrame,所以不需要

freq = sns.load_dataset(freq_data)

此外,您可能希望在 freq_data 中使用 iris 而不是 df = sns.pairplot(iris,hue="condition",height=2.5)

这是最终的示例代码

from io import StringIO
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

TESTDATA = StringIO("""condition;area;sphericity;aspect_ratio
20 kHz;0.249;0.287;1.376
20 kHz;0.954;0.721;1.421
20 kHz;0.118;0.260;1.409
20 kHz;0.540;0.552;1.526
20 kHz;0.448;0.465;1.160
30 kHz;6.056;0.955;2.029
30 kHz;4.115;1.097;1.398
30 kHz;11.055;1.816;1.838
30 kHz;4.360;1.183;1.162
30 kHz;10.596;0.940;1.715
    """)

freq_data = pd.read_csv(TESTDATA,sep=";")

sns.pairplot(freq_data,height=2.5)
plt.show()

enter image description here

DataFrame 的真值是不明确的在 Jupyter 中使用 a.empty、a.bool()、a.item()、a.any() 或 a.all() 错误

DataFrame 的真值是不明确的在 Jupyter 中使用 a.empty、a.bool()、a.item()、a.any() 或 a.all() 错误

如何解决DataFrame 的真值是不明确的在 Jupyter 中使用 a.empty、a.bool()、a.item()、a.any() 或 a.all() 错误

enter image description here

我对 Python 非常陌生,我正在尝试执行代码,它给了我这个错误。我阅读了与 Null 值相关的内容。谁能告诉我我能做些什么来解决它?

关于Pandas python ValueError:DataFrame 的真值不明确使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于'bool?' 类型的值不能分配给类型为 'bool' 的变量,因为 'bool?'可以为空,而 'bool' 不是、Apply 和 Lambda 函数 - ValueError:系列的真值不明确使用 a.empty、a.bool()、a.item()、a.any() 或 a.all() 修复更好、Dataframe 的真值是不明确的使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()、DataFrame 的真值是不明确的在 Jupyter 中使用 a.empty、a.bool()、a.item()、a.any() 或 a.all() 错误等相关内容,可以在本站寻找。

本文标签: