Home > Back-end >  Is there a way to create a dataframe in python from start date to end date
Is there a way to create a dataframe in python from start date to end date

Time:11-08

Is there way to create a dataframe(using pandas) from start date to End date with random values

For example,

Required dataframe

df
date          value 
2015-06-25     12
2015-06-26     23
2015-06-27     3.4
2015-06-28     5.6

Is this dataframe I need to set "from date" to "To date" so that there is no need to type manually because the rows keep on increasing and "value" column should have values generated randomly

CodePudding user response:

You can use pandas.date_range and numpy.random.uniform:

import numpy as np
dates = pd.date_range('2015-06-25', '2015-06-28', freq='D')

df = pd.DataFrame({'date': dates,
                   'value': np.random.uniform(0, 50, size=len(dates))})

output:

        date      value
0 2015-06-25  39.496971
1 2015-06-26  29.947877
2 2015-06-27   7.328549
3 2015-06-28   6.738427

CodePudding user response:

import pandas as pd
import numpy as np
beg = '2015-06-25 '
end = '2015-06-28'
index = pd.date_range(beg, end)
values = np.random.rand(len(index))
df = pd.DataFrame(values, index=index)
index 0
2015-06-25 00:00:00 0.865455754057059
2015-06-26 00:00:00 0.959574113247196
2015-06-27 00:00:00 0.8634928651970131
2015-06-28 00:00:00 0.6448579391510935

CodePudding user response:

Use date_range with numpy.random.rand:

np.random.seed(42)

r = pd.date_range('2015-06-25', '2015-06-28')
df = pd.DataFrame({'date': r, 'value':np.random.rand(len(r))})
print (df)
        date     value
0 2015-06-25  0.374540
1 2015-06-26  0.950714
2 2015-06-27  0.731994
3 2015-06-28  0.598658
  • Related