使用日期时间索引和列中的随机值创建pandas数据帧

时间:2020-11-29 21:24:11

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

如何创建一个以datetime为索引的pandas数据框,以及列的随机值。目前,我有这个:

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?

我该怎么从这里开始?

3 个解决方案

#1


5  

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

#2


2  

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')

#3


0  

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0,30,size=10),
                  columns=["Random"],
                  index=pd.date_range("20180101", periods=10))

#1


5  

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

#2


2  

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')

#3


0  

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0,30,size=10),
                  columns=["Random"],
                  index=pd.date_range("20180101", periods=10))