发布于2021-01-17 16:46 阅读(533) 评论(0) 点赞(10) 收藏(1)
0
1
2
3
4
我使用numpy创建了给定大小的随机矩阵。对于时间序列仿真,我为对应的矩阵创建了一个频率为一个月的时间序列。现在,我想将它们组合起来,并作为熊猫数据框使用。这是我到目前为止所拥有的-
import numpy as np
import pandas as pd
cols = ['time', 'cases', 'deaths', 'recoveries']
data = np.random.randint(0,50,(50,3))
times = pd.date_range('2019-12-01', periods=50, freq='MS')
df = pd.DataFrame(pd.concat(times, data, ignore_index=True), columns=cols)
这在第8行给出了以下错误-
TypeError: cannot concatenate object of type '<class 'pandas._libs.tslibs.timestamps.Timestamp'>'; only Series and DataFrame objs are valid
所以我尝试将其转换为系列,times = pd.Series(pd.date_range('2019-12-01', periods=50, freq='MS'))
但是反过来又给出了错误-
TypeError: first argument must be an iterable of pandas objects, you passed an object of type "Series"
预计O / P -
| time |cases|deaths|recoveries|
|------------------------------------|
| 2019-12-01 | 0 | 0 | 0 |
| 2020-01-01 | 1 | 0 | 0 |
| 2020-02-01 | 2 | 1 | 0 |
我建议创建DatetimeIndex
列,以便通过datetimelike方法处理熊猫:
#removed time column
cols = ['cases', 'deaths', 'recoveries']
data = np.random.randint(0,50,(50,3))
#added time in name parameter
times = pd.date_range('2019-12-01', periods=50, freq='MS', name='time')
#removed concat and added index parameter
df = pd.DataFrame(data, columns=cols, index=times)
print (df.head(10))
cases deaths recoveries
time
2019-12-01 28 44 25
2020-01-01 21 23 26
2020-02-01 15 17 5
2020-03-01 35 3 42
2020-04-01 46 7 3
2020-05-01 23 47 28
2020-06-01 31 30 34
2020-07-01 8 4 15
2020-08-01 46 14 24
2020-09-01 43 47 6
如果需要只添加列DataFrame.reset_index
:
df = pd.DataFrame(data, columns=cols, index=times).reset_index()
print (df.head(10))
time cases deaths recoveries
0 2019-12-01 2 26 43
1 2020-01-01 43 40 41
2 2020-02-01 23 12 22
3 2020-03-01 43 37 28
4 2020-04-01 7 26 20
5 2020-05-01 19 46 41
6 2020-06-01 43 1 0
7 2020-07-01 19 42 4
8 2020-08-01 14 39 40
9 2020-09-01 15 8 25
0
1
2
3
4
5
6
7
8
9
作者:黑洞官方问答小能手
链接: https://www.pythonheidong.com/blog/article/777276/ccc50483623c4aae7e76/
来源: python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系z452as@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!