【问题标题】:Pandas dataframe issue with date time when using functions使用函数时日期时间的 Pandas 数据框问题
【发布时间】:2021-04-11 00:59:30
【问题描述】:

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

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

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

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,但它抛出了 '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

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

【问题讨论】:

  • date_convert = print()。我猜你需要删除print()

标签: python pandas function date


【解决方案1】:

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

通过这样做:

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

date_convert 将是 NoneType

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-31
    • 2021-06-04
    • 2021-05-09
    • 1970-01-01
    • 2018-11-12
    • 2023-03-09
    • 1970-01-01
    • 2019-07-14
    相关资源
    最近更新 更多