python - 如何根据日期时间值创建列?
问题描述
我想由另一个 dtype 为 datetime 的列创建一个列。详情如下:
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 函数。
也不推荐,因为慢。但解决方案是将字符串转换为Timestamp
or datetime
:
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)
推荐阅读
- ios - nativescript angular 应用程序在 ios 上使用 firebase 静默崩溃
- maven - 使用 mvn clean verify 执行时 exec-maven 插件错误
- debugging - 无法使用 blazor 进行调试(缺少文件://)
- python - 无法在我的 beta 计算器中更改雅虎价格数据的时间间隔
- reactjs - React JS,文件未使用 https 上传到节点服务器
- variables - 如何以单独的方法打印多项式?
- reactjs - 如何在 useReducer 中进行 api 调用?
- macos - ModuleNotFoundError:没有名为“pip._vendor.certifi”的模块
- elasticsearch - Elastalert 过滤日志级别并发送电子邮件
- java - 如何在课堂外使用列表?