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?
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
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With