Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating pandas dataframe with datetime index and random values in column

Tags:

python

pandas

How do I create a pandas dataframe with datetime as index, and random values for a column. Currently, I have this:

from datetime import datetime, timedelta

date_today = datetime.now()
date_end = date_today + timedelta(7)

df = pd.DataFrame(columns=['test'])

How do I proceed from here?

like image 871
user308827 Avatar asked Mar 22 '17 01:03

user308827


Video Answer


2 Answers

You can try this:

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

date_today = datetime.now()
days = pd.date_range(date_today, date_today + timedelta(7), freq='D')

np.random.seed(seed=1111)
data = np.random.randint(1, high=100, size=len(days))
df = pd.DataFrame({'test': days, 'col2': data})
df = df.set_index('test')
print(df)


test                            
2017-03-22 10:07:41.914019    29
2017-03-23 10:07:41.914019    56
2017-03-24 10:07:41.914019    82
2017-03-25 10:07:41.914019    13
2017-03-26 10:07:41.914019    35
2017-03-27 10:07:41.914019    53
2017-03-28 10:07:41.914019    25
2017-03-29 10:07:41.914019    23
like image 194
Joe T. Boka Avatar answered Oct 20 '22 12:10

Joe T. Boka


My code for your reference

from datetime import datetime, timedelta
import pandas as pd
import numpy as np

date_today = datetime.now()
ndays = 7
df = pd.DataFrame({'date': [date_today + timedelta(days=x) for x in range(ndays)], 
                   'test': pd.Series(np.random.randn(ndays))})
df = df.set_index('date')
like image 29
Shane Kao Avatar answered Oct 20 '22 12:10

Shane Kao