首页 > 解决方案 > 从熊猫的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

标签: pythonregexpandastimedelta

解决方案


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

推荐阅读