Creating pandas dataframe with datetime index and random values in column

前端 未结 3 636
抹茶落季
抹茶落季 2020-12-28 09:03

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

         


        
相关标签:
3条回答
  • 2020-12-28 09:39

    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
    
    0 讨论(0)
  • 2020-12-28 09:39

    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')
    
    0 讨论(0)
  • 2020-12-28 10:01
    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))
    
    0 讨论(0)
提交回复
热议问题