【问题标题】:Converting dataframe to list of tuples changes datetime.datetime to int将数据框转换为元组列表将 datetime.datetime 更改为 int
【发布时间】:2021-07-10 02:42:29
【问题描述】:

我有一些使用 Pandas 编写的代码,可以进行我想要的确切处理,但不幸的是速度很慢。为了加快处理时间,我将数据帧转换为元组列表,其中每个元组都是数据帧中的一行。

我发现 datetime.datetime 对象被转换为长整数,例如 1622623719000000000。

我需要计算每一行之间的时间差,所以我的想法是‘好吧,我不擅长 python/pandas,但我知道我可以通过 datetime.fromtimestamp(1622623719000000000) 来获取日期时间对象。

不幸的是,datetime.fromtimestamp(1622623719000000000) 抛出 OSError: [Errno 22] Invalid argument

因此,请前往 Google/SO 寻找解决方案。我发现this example 显示将长整数除以1e3。我尝试过,但仍然得到“无效参数”。

我玩弄 long int 的除法,除以 1e9 让我最接近原始 datetime.datetime 值,但不完全。

如何成功地将 long int 转换回正确的日期时间值?

将字符串格式转换为日期时间的代码:

df.start_time = pd.to_datetime(df.report_date + " " + df.start_time)

数据框信息:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 46 entries, 0 to 45
Data columns (total 19 columns):
report_date      46 non-null object
...
...
...
start_time       46 non-null datetime64[ns]
...
...
...

dtypes: datetime64[ns](1), float64(7), int64(1), object(10)
memory usage: 6.9+ KB
None

我的测试代码:

print("DF start time", df.start_time[5], "is type", type(df.start_time[5]))
print("list start time", tup_list[5][7], "is type", type(tup_list[5][7]),"\n")

print("Convert long int in row tuple to datetime")
print(datetime.fromtimestamp(int(1622623719000000000/1e9)))

输出:

DF start time 2021-06-02 08:16:33 is type <class 'pandas._libs.tslibs.timestamps.Timestamp'>
list start time 1622623719000000000 is type <class 'int'> 

Convert int in row tuple to datetime
2021-06-02 03:48:39

【问题讨论】:

    标签: python pandas datetime


    【解决方案1】:

    更改列start_time 的dtype 以将Timestamp 转换为整数(纳秒):

    df = pd.DataFrame({'start_time': ['2021-06-02 08:16:33']}) \
           .astype({'start_time': 'datetime64'})
    
    >>> df
               start_time
    0 2021-06-02 08:16:33
    
    >>> df['start_time'].astype(int)
    0    1622621793000000000  # NOT 1622623719000000000
    Name: start_time, dtype: int64
    
    >>> pd.to_datetime(1622621793000000000)  # Right
    Timestamp('2021-06-02 08:16:33')
    
    >>> pd.to_datetime(1622623719000000000)  # Wrong
    Timestamp('2021-06-02 08:48:39')
    

    【讨论】:

    • 或者您的索引可能不好。您的数据框中Timestamp('2021-06-02 08:48:39') 之前和之后的值是什么?
    • 我复制/粘贴了上面的代码,将列转换为astype(int),得到了TypeError: cannot astype a datetimelike from [datetime64[ns]] to [int32]。我从字符串格式转换为日期时间的原始代码 - df.start_time = pd.to_datetime(df.start_time)
    • 请使用原始数据框示例和df.info() 的输出更新您的代码。
    • 按要求添加到原始帖子中。
    • 你的 Python 版本是多少?你在使用 32 位机器(int32)吗?如果你想解决问题,我认为你应该使用df['start_time'].astype(np.int64)。我可以通过以下方式重现您的错误:df['start_time'].astype(np.int32)
    【解决方案2】:

    我解决了这个问题,可能一开始就应该解决这个问题。

    我最初将我的数据框转换为元组列表以加快行处理:

    df.to_records(index=False).tolist()
    

    不幸的是,在转换过程中,df.start_time 中的值从 &lt;class 'pandas._libs.tslibs.timestamps.Timestamp'&gt; 转换为 &lt;class int&gt;

    解决办法:

    df.to_dict('records')
    

    这会将df.start_time 中的数据保留为Timestamp 类型:

    'start_time': Timestamp('2021-06-02 08:16:33')
    

    经验教训。

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-28
      • 2018-02-03
      • 2017-12-30
      相关资源
      最近更新 更多