gpt4 book ai didi

python - 如何根据日期时间值创建列?

转载 作者:行者123 更新时间:2023-12-01 08:19:57 24 4
gpt4 key购买 nike

我想用另一列创建一个数据类型为日期时间的列。详情如下:

 df['finished']

0 2019-01-28 15:53:48
1 2019-01-28 17:11:15
2 2019-01-28 17:12:14
3 2019-01-28 17:12:15
4 2019-01-28 17:12:41
Name: finish, dtype: datetime64[ns]

df['finish'].map(lambda x: 30 if x<='2019-02-01 21:00:00' else 5)

TypeError: Cannot compare type 'Timestamp' with type 'str

最佳答案

如果以 pandas 矢量化方式进行比较 - 所有具有值的列,则无需转换为日期时间,因为 pandas 处理此比较:

df['new'] = np.where(df['finish'] <='2019-02-01 21:00:00', 30, 5)
print (df)
finish new
0 2019-01-28 15:53:48 30
1 2019-01-28 17:11:15 30
2 2019-01-28 17:12:14 30
3 2019-01-28 17:12:15 30
4 2019-01-28 17:12:41 30

您的解决方案失败了,因为比较标量,因此有必要在循环中按日期时间进行比较 - 为每个值调用 lambda 函数。

也不推荐,因为慢。但解决方案是将字符串转换为 Timestampdatetime:

df['new'] = df['finish'].map(lambda x: 30 if x<=pd.Timestamp('2019-02-01 21:00:00') else 5)

性能:

#[5000 rows x 1 columns]
df = pd.concat([df] * 1000, ignore_index=True)

In [165]: %timeit df['new1'] = np.where(df['finish'] <='2019-02-01 21:00:00', 30, 5)
465 µs ± 64.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [166]: %timeit df['new2'] = df['finish'].map(lambda x: 30 if x<=pd.Timestamp('2019-02-01 21:00:00') else 5)
22.4 ms ± 228 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

关于python - 如何根据日期时间值创建列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54708761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com