Screenshot of dataframe I am working on
I want to convert the values in df['Chip Time'] column which are string obj to timedelta64.
Have tried this....> df2['Chip Time'] = pd.to_timedelta(df2['Chip Time'])
BUT GETS Error message ...> ValueError: expected hh:mm:ss format
CodePudding user response:
You can add :00
if string has only one :
by Series.str.count
with Series.mask
:
df2 = pd.DataFrame({"Chip Time": ['10:04','1:45:23','23:12']})
s = df2['Chip Time'].mask(df2['Chip Time'].str.count(':').eq(1), df2['Chip Time'] ':00')
#alternative:
#s = df2['Chip Time'] np.where(df2['Chip Time'].str.count(':').eq(1), ':00', '')
print (s)
0 10:04:00
1 1:45:23
2 23:12:00
Name: Chip Time, dtype: object
df2['Chip Time'] = pd.to_timedelta(s)
print (df2)
Chip Time
0 0 days 10:04:00
1 0 days 01:45:23
2 0 days 23:12:00
CodePudding user response:
You can use a regex with str.replace
to add '0:'
on values matching 'x:x'
only:
df2['Chip Time'] = pd.to_timedelta(df2['Chip Time'].str.replace('^(\d :\d )$', r'0:\1', regex=True))
Example output:
Chip Time
0 0 days 00:16:48
1 0 days 01:07:51
Used input:
Chip Time
0 16:48
1 1:07:51