Replace A Single Character In A Numpy List Of Strings
I have a Numpy array of datetime64 objects that I need to convert to a specific time format yyyy-mm-dd,HH:MM:SS.SSS Numpy has a function called datetime_as_string that outputs ISO
Solution 1:
You could use viewcasting to get access to individual characters:
time_strings[...,None].view('U1')[...,10] =','
changes time_strings
in-place.
Solution 2:
In [309]: np.char.replace(time_strings,'T',',')
Out[309]:
array(['1970-01-01,00:00:00.000', '1970-01-01,00:00:00.001',
'1970-01-01,00:00:00.002', '1970-01-01,00:00:00.003',
'1970-01-01,00:00:00.004', '1970-01-01,00:00:00.005',
'1970-01-01,00:00:00.006', '1970-01-01,00:00:00.007',
....
But @PaulPanzer's inplace is much faster (even it is a bit more obscure):
In [316]: %%timeit temp=time_strings.copy()
...: temp[...,None].view('U1')[...,10] =','8.48 µs ± 34.3 ns per loop (mean ± std. dev. of7 runs, 100000 loops each)
In [317]: timeit np.char.replace(time_strings,'T',',')
1.23 ms ± 1.12 µs per loop (mean ± std. dev. of7 runs, 1000 loops each)
Post a Comment for "Replace A Single Character In A Numpy List Of Strings"