python - 从熊猫的timedelta列中提取天数
问题描述
我有一个存储老化值的数据框,如下所示:
Aging
-84 days +11:36:15.000000000
-46 days +12:25:48.000000000
-131 days +20:53:45.000000000
-131 days +22:22:50.000000000
-130 days +01:02:03.000000000
-80 days +17:02:55.000000000
我正在尝试days
在上列中提取文本。我尝试了以下方法:
df['new'] = df.Aging.split('days')[0]
以上返回
AttributeError: 'Series' object has no attribute 'split'
预期输出:
-84
-46
-131
-131
-130
-80
解决方案
IMO,一个更好的主意是转换timedelta
并提取天数组件。
pd.to_timedelta(df.Aging, errors='coerce').dt.days
0 -84
1 -46
2 -131
3 -131
4 -130
5 -80
Name: Aging, dtype: int64
如果你坚持使用字符串方法,你可以使用str.extract
.
pd.to_numeric(
df.Aging.str.extract('(.*?) days', expand=False),
errors='coerce')
0 -84
1 -46
2 -131
3 -131
4 -130
5 -80
Name: Aging, dtype: int32
或者,使用str.split
pd.to_numeric(df.Aging.str.split(' days').str[0], errors='coerce')
0 -84
1 -46
2 -131
3 -131
4 -130
5 -80
Name: Aging, dtype: int64
推荐阅读
- javascript - 测量页面加载和 iframe 加载
- cplex - 当我修改约束 (GLPK) 的 RHS 时会发生什么?
- hibernate - Hibernate.cfg.xml 与 Persistence.xml
- javascript - 异步/等待的竞争条件
- firebase - Firebase 的身份验证 UID 是如何生成的?
- r - 从变量中选择某些词
- postgresql - 在postgresql sql中组合计数和最大值
- python-3.x - 将列表理解与 Pandas 系列和数据框一起使用
- javascript - 如何在带有 AJAX 的客户端中使用 JWT
- javascript - 如何使用jquery中的filter函数来过滤div内的一组数据?