【问题标题】:Converting string of lists of timestamps to lists of timestamps in pandas将时间戳列表字符串转换为熊猫中的时间戳列表
【发布时间】:2021-08-13 10:02:22
【问题描述】:

我从 s3 解析的数据与此类似

ID   departure
1    "[Timestamp('2021-05-25 09:00:00'), datetime.datetime(2021, 5, 25, 9, 21, 35, 769406)]"
2    "[Timestamp('2021-05-25 08:00:00'), datetime.datetime(2021, 5, 25, 11, 15), datetime.datetime(2021, 5, 25, 14, 15)]"

有没有办法将departure 转换成列表

我试过了

samp['departure'] = samp['departure'].apply(lambda x: eval(x))
-> Error: eval() arg 1 must be a string, bytes or code object

samp['departure'] = samp['departure'].apply(lambda x: x[1:-1].split(','))
# Here datetime.datetime(2021, 5, 25, 11, 15) splited into many sub-parts

samp.departure = samp.departure.apply(ast.literal_eval)
error -> malformed node or string: ["Timestamp('2021-05-25 09:00:00')", ' datetime.datetime(2021', ' 5', ' 25', ' 9', ' 21', ' 35', ' 769406)']

输出应该是

ID   departure
1    [Timestamp('2021-05-25 09:00:00'), datetime.datetime(2021, 5, 25, 9, 21, 35, 769406)]
2    [Timestamp('2021-05-25 08:00:00'), datetime.datetime(2021, 5, 25, 11, 15), datetime.datetime(2021, 5, 25, 14, 15)]

(我最初在 read_csv 时尝试过转换器,但也遇到了错误)

【问题讨论】:

  • samp['departure'] = samp['departure'].apply(lambda x: eval(x)) 中的 x 是什么?这似乎是字符串,但显然错误另有说明。

标签: python pandas


【解决方案1】:

如果您尝试替换离开列中的"

通过replace()尝试:

samp['departure']=samp['departure'].replace('"','',regex=True)

通过strip()尝试:

samp['departure']=samp['departure'].str.strip('"')

如果你正在评估里面的值:

from pandas import Timestamp
import datetime
samp['departure']=samp['departure'].astype(str).apply(pd.eval)

from pandas import Timestamp
import datetime
import ast
samp.departure = samp.departure.astype(str).apply(ast.literal_eval)

【讨论】:

    猜你喜欢
    • 2020-04-16
    • 1970-01-01
    • 2017-11-28
    • 2017-08-05
    • 1970-01-01
    • 2020-11-22
    • 2020-12-01
    • 1970-01-01
    相关资源
    最近更新 更多