使用函数时出现日期时间的熊猫数据框问题

时间:2021-04-11 00:59:30

标签: python pandas function date

我正在使用两个函数来过滤掉一些值,例如删除空值。这些函数似乎工作正常,但在某些时候将列转换为日期类型时会出现问题。它有效,但不完全。

在这里,我将第一个函数值传递给第二个函数,因为第二个函数需要返回值作为它的参数

当我打印函数的结果时。我得到以下信息:

print(is_string_date_in_right_format(remove_null(df)))

# returns a table with 
id , color , date (in string format)
1  , red   ,  '05/01/2012'
        
-- here i am converting the 3rd column to datetime
date_conv = is_string_date_in_right_format(remove_null(df))['date'] = pd.to_datetime(is_string_date_in_right_format(remove_null(df))["date"])

print(date_conv) # shows all the dates converted to DateTime (which is what I want)

results:
2021-05-01
2021-01-01
and so on.....

但是,当我尝试通过根据时间范围选择数据来进行比较时,它不会像运行上面的打印语句时那样向我显示带有 DateTime 的数据,因为下面的代码也不起作用.我正在尝试以下操作:

我试图在下面的第二行代码中直接使用变量 date_conv 但它抛出了“关键错误”

date_convert = print(is_string_date_in_right_format(remove_null(df)))      

required_id = (date_convert['date'] >= date1) & (date_convert['date'] <= date_2) 

new_d = date_convert[required_id]

print(new_d) # shows me no results it says empty data frame

--日期1和日期2的格式为2021-04-19(同上面的打印语句)

1 个答案:

答案 0 :(得分:0)

正如有人已经提到的,不要将 print() 的结果分配给变量。 您需要一个 DataFrame,因此分配语句应返回一个。否则,您将在以下句子中得到 KeyError,因为 date_convert 没有任何值或不是预期的格式。

这样做:

date_convert = print(is_string_date_in_right_format(remove_null(df)))

date_convert 将是 NoneType

此外,一个名为 is_... 的函数让人认为该函数返回的是一个布尔值而不是一个 DataFrame。建议你改一下函数名,以免混淆。

相关问题