分割时间格式化的对象不适用于python和pandas

时间:2019-12-20 18:38:56

标签: python-3.x

我有简单的代码行:

print(df['Duration'])
df['Duration'].str.split(':')
print(df['Duration'])

这是我每次打印的值

00:58:59
00:27:41
00:27:56
Name: Duration, dtype: object

为什么拆分在这里不起作用?我缺少什么?

1 个答案:

答案 0 :(得分:1)

str.split不会在原位置修改,因此您需要将结果分配给以下内容:

import pandas as pd

df = pd.DataFrame({'Duration':['00:58:59', '00:27:41', '00:27:56'], 'other':[10, 20, 30]})

df['Duration'] = df['Duration'].str.split(':')
print(df)

打印:

       Duration  other
0  [00, 58, 59]     10
1  [00, 27, 41]     20
2  [00, 27, 56]     30

如果要通过拆分扩展DataFrame的列,可以尝试:

import pandas as pd

df = pd.DataFrame({'Duration':['00:58:59', '00:27:41', '00:27:56'], 'other':[10, 20, 30]})

df[['hours', 'minutes', 'seconds']] = df['Duration'].str.split(':', expand=True)
print(df)

打印:

   Duration  other hours minutes seconds
0  00:58:59     10    00      58      59
1  00:27:41     20    00      27      41
2  00:27:56     30    00      27      56