【问题标题】:Find if a column in dataframe has neither nan nor none查找数据框中的列是否既没有 nan 也没有 none
【发布时间】:2019-01-05 02:03:58
【问题描述】:

我浏览了网站上的所有帖子,但无法找到解决问题的方法。

我有一个包含 15 列的数据框。其中一些带有NoneNaN 值。我需要帮助来编写 if-else 条件。

如果数据框中的列不为 null 和 nan,我需要格式化 datetime 列。当前代码如下

for index, row in df_with_job_name.iterrows():
    start_time=df_with_job_name.loc[index,'startTime']
    if not df_with_job_name.isna(df_with_job_name.loc[index,'startTime']) :
        start_time_formatted =
            datetime(*map(int, re.split('[^\d]', start_time)[:-1]))

我得到的错误是

if not df_with_job_name.isna(df_with_job_name.loc[index,'startTime']) :
TypeError: isna() takes exactly 1 argument (2 given)

【问题讨论】:

  • 谢谢我尝试使用 null_map_df = df_with_job_name.isna()。它适用于少量测试记录。但是,当我在此数据框中迭代 700 多个项目时,它为 nan 值之一返回 false

标签: python pandas


【解决方案1】:

处理缺失/无效值的直接方法可能是:

def is_valid(val):
    if val is None:
       return False
    try:
       return not math.isnan(val)
    except TypeError:
       return True

当然你必须导入math

另外,isna 似乎没有使用任何参数调用并返回布尔值的数据帧(请参阅link)。您可以遍历两个数据帧以确定该值是否有效。

【讨论】:

    【解决方案2】:

    isna 将您的整个数据框作为实例参数(即self,如果您已经熟悉类)并返回布尔值的数据框True,其中该值无效。您尝试将要检查的单个值指定为第二个输入参数。 isna 不是这样工作的;它在调用中需要空括号。

    您有几个选择。一种是遵循个人检查策略here。另一种是制作整个数据框的地图并使用它:

    null_map_df = df_with_job_name.isna()
    
    for index, row in df_with_job_name.iterrows() :
        if not null_map_df.loc[index,row]) :
            start_time=df_with_job_name.loc[index,'startTime']
            start_time_formatted =
                datetime(*map(int, re.split('[^\d]', start_time)[:-1]))
    

    请检查我对行和列索引的使用; index, row 处理看起来不正确。此外,您应该能够一次将any 操作应用于整行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-19
      • 2014-10-10
      • 2021-12-23
      • 2012-08-13
      • 1970-01-01
      • 2017-10-28
      • 2011-10-19
      相关资源
      最近更新 更多