在数据框中查找某一列是否既没有nan也没有非数字(non)

2024-06-06 08:09:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

如果dataframe中的列不是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)

Tags: namedfdatetimeindexiftime网站with
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操作

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

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

当然,您必须导入math

而且isna似乎没有用任何参数调用,而是返回一个布尔值的数据帧(参见link)。您可以遍历这两个数据帧来确定值是否有效

相关问题 更多 >