I am new to pandas and practicing some basic functionalities. I have a CSV file which contains some data of every minute of some date. After reading CSV, df.head()
gives the following result :
Time C1 C2 C3 C4 C5 C6
0 2016-05-25 03:15:00 0 0 0 0 0 0
1 2016-05-25 03:16:00 0 0 0 0 0 0
2 2016-05-25 03:17:00 0 0 2 0 0 0
3 2016-05-25 03:18:00 0 0 0 5 0 2
4 2016-05-25 03:19:00 0 0 0 0 0 5
I have used parse_dates
option of pd.read_csv
. Hence, Time is in datetime64[ns]
format. Since, the date is the same I don't want to have that on my column. So, I use
df['Time']=df['Time'].dt.time
It does what I want but it changes the format to object
, which I didn't want. Upon suggestions of some other answers, I did the following :
df['Time']=pd.to_datetime(df['Time'], format="%H:%M:%S")
df['Time'].head()
0 1900-01-01 03:15:00
1 1900-01-01 03:16:00
2 1900-01-01 03:17:00
3 1900-01-01 03:18:00
4 1900-01-01 03:19:00
Name: Time, dtype: datetime64[ns]
This converted the column into datetime64[ns]
but added an additional date. Is it possible to convert just time into datetime64[ns]
?
No, it is not possible. For datetimes always need dates.
But if need working with times, better is use timedelta
s by strftime
for strings HH:MM:SS
with to_timedelta
:
df['Time'] = pd.to_timedelta(df['Time'].dt.strftime('%H:%M:%S'))
print (df)
Time C1 C2 C3 C4 C5 C6
0 03:15:00 0 0 0 0 0 0
1 03:16:00 0 0 0 0 0 0
2 03:17:00 0 0 2 0 0 0
3 03:18:00 0 0 0 5 0 2
4 03:19:00 0 0 0 0 0 5
print (df.dtypes)
Time timedelta64[ns]
C1 int64
C2 int64
C3 int64
C4 int64
C5 int64
C6 int64
dtype: object
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.