Prayuktibid
Prayuktibid

Reputation: 189

How to add numpy datetime list into Pandas Dataframe as column?

I have created a datetime list with 15min interval using this code

import pandas as pd
import numpy as np
power_data = pd.DataFrame([])
time_data = []
time_data = np.arange('2017-10-31T00:15', '2017-12-01T00:15', dtype='datetime64[15m]'))

the output which I getting is okay as per expected. thereafter I try to add this date time array as column into panadas dataframe using this code

time_data = pd.Series(time_data)
power_data['Time'] = time_data.values 

This code added this Time column correctly but the DateTime value has been changed.

0      1973-03-10 16:01:00
1      1973-03-10 16:02:00
2      1973-03-10 16:03:00
.........
2975   1973-03-12 17:36:00

The main culprit is pd.Series(time_data) which changed the datetime value when it arranging is series. My question is how I can add this datetime without changing it's value?

Upvotes: 1

Views: 1659

Answers (2)

Mewtwo
Mewtwo

Reputation: 1311

import pandas as pd
import numpy as np
power_data = pd.DataFrame([])
time_data = []
time_data = np.arange('2017-10-31T00:15', '2017-12-01T00:15',  dtype='datetime64')
time_data

I have just removed the [15m]. Everything else remains the same. So:

time_data =  pd.Series(time_data) 
power_data['Time'] = time_data.values
power_data

Now the power_data output looks like this:

0   2017-10-31 00:15:00
1   2017-10-31 00:16:00
2   2017-10-31 00:17:00
3   2017-10-31 00:18:00

Upvotes: 2

rpanai
rpanai

Reputation: 13437

Have you consider use pd.date_range() instead?

This works for me:

power_data = pd.DataFrame([])
power_data["Time"] = pd.date_range(start="2017-10-31 00:15:00",
                                   end = '2017-12-01 00:15:00',
                                   freq = '15T' )

Upvotes: 2

Related Questions