我有简单的代码行:
print(df['Duration'])
df['Duration'].str.split(':')
print(df['Duration'])
这是我每次打印的值
00:58:59
00:27:41
00:27:56
Name: Duration, dtype: object
为什么拆分在这里不起作用?我缺少什么?
答案 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