python—有没有一种方法可以在不使用循环的情况下,将一列添加到一个对另一列的数据执行datetime操作的列表中?

gwo2fgha  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(245)

我正试图用pyplot绘制一个时间序列。我有一个二维numpy数组,其中的时间数据如下所示(截断数组):

sndTemps_time = array([[ 0.      ,  0.      ],
           [ 0.041667,  1.      ],
           [ 0.083333,  2.      ],
           [ 0.125   ,  3.      ]]).

第一列表示模拟开始后的天数,第二列表示一天中的小时数。
y轴数据由numpy数组表示 avg_temps_in_z . 目前,我正在绘制(有更多的代码,但这里的要点):

figure_handle,ax2 = plt.subplots()
ax2.plot(sndTemps_time[:,0],avg_temps_in_z)

要得到一个x轴标记为“模拟开始后的天数”的图,但实际上我想生成一个x轴上有实际日期的图。
我有一个变量 start_date ,它是日期时间格式:

start_date = datetime.datetime(2020, 12, 24, 0, 0)

我知道我可以使用循环获取日期时间列表,使用:


# create an empty list for the dates

sndTemps_dates = [0]*sndTemps_time.shape[0]

# put start date in top row of list

sndTemps_dates[0] = start_date

for d in range(1,sndTemps_time.shape[0]):
    sndTemps_dates[d] = start_date + timedelta(days=sndTemps_time[d,0])

哪里 sndTemps_dates 是新的列表,但是有没有一种方法可以不用循环,使用pandas Dataframe 或numpy数组来实现这一点?
这与前面的问题不同

luaexgnf

luaexgnf1#

我简化了你的问题:

a = pd.DataFrame([100, 200, 300, 400], columns = ['example'])
print('this is before adding a column')
print(a)
a['new_col'] = a['example'][0]
print('this is after adding a column')
print(a)

输出:

this is before adding a column
   example
0      100
1      200
2      300
3      400
this is after adding a column
   example  new_col
0      100      100
1      200      100
2      300      100
3      400      100

我认为做类似的事情你就能解决你的问题。

相关问题