Python 使用函数时,数据帧问题与日期时间有关

Python 使用函数时,数据帧问题与日期时间有关,python,pandas,function,date,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

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

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

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

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.....
但是,当我试图通过基于时间段选择数据来进行比较时,它不会像我运行上面的print语句时那样显示带有日期时间的数据,因此下面的代码也无法工作。我正在尝试以下方法:

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.....
我试图在下面的第二行代码中直接使用变量date_conv,但它抛出了“Key Error”

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
date\u convert=print(是字符串格式的日期格式(删除空值(df)))

必需的\u id=(date\u convert['date']>=date1)和(date\u convert['date']]正如前面提到的,不要将
print()
的结果分配给变量。 您需要一个数据帧,因此assign语句应该返回一个数据帧。否则,由于
date\u convert
没有任何值或格式不符合要求,您将在以下语句中得到一个
KeyError

通过这样做:

date_convert = print(is_string_date_in_right_format(remove_null(df)))
date\u convert
将是
NoneType

此外,一个名为
的函数是…
会让人觉得该函数返回的是布尔值而不是数据帧。我建议您更改函数名以避免混淆。

date\u convert=print()
。我想您需要删除
print()