Python 有没有办法将熊猫系列/日期时间系列与相同行的numpy矩阵连接起来?
我用numpy创建了一个给定大小的随机矩阵。对于时间序列模拟,我为相应的矩阵创建了一个频率为一个月的时间序列。现在我想将它们组合起来,并将它们作为一个数据帧。这就是我目前所拥有的- 将numpy作为np导入 作为pd进口熊猫 cols=[‘时间’、‘病例’、‘死亡’、‘恢复’] 数据=np.random.randint0,50,50,3 时间=pd.日期范围'2019-12-01',周期=50,频率=MS' df=pd.DataFramepd.concattimes,data,ignore_index=True,columns=cols 这在第8行给出了以下错误-Python 有没有办法将熊猫系列/日期时间系列与相同行的numpy矩阵连接起来?,python,pandas,numpy,dataframe,series,Python,Pandas,Numpy,Dataframe,Series,我用numpy创建了一个给定大小的随机矩阵。对于时间序列模拟,我为相应的矩阵创建了一个频率为一个月的时间序列。现在我想将它们组合起来,并将它们作为一个数据帧。这就是我目前所拥有的- 将numpy作为np导入 作为pd进口熊猫 cols=[‘时间’、‘病例’、‘死亡’、‘恢复’] 数据=np.random.randint0,50,50,3 时间=pd.日期范围'2019-12-01',周期=50,频率=MS' df=pd.DataFramepd.concattimes,data,ignore_in
TypeError: cannot concatenate object of type '<class 'pandas._libs.tslibs.timestamps.Timestamp'>'; only Series and DataFrame objs are valid
预期O/p-
我建议创建DatetimeIndex而不是列,以便通过类似DatetimeIndex的方法进行处理:
#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
如果需要,只添加以下列:
| time |cases|deaths|recoveries|
|------------------------------------|
| 2019-12-01 | 0 | 0 | 0 |
| 2020-01-01 | 1 | 0 | 0 |
| 2020-02-01 | 2 | 1 | 0 |
#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
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