首页 > 解决方案 > 有没有办法在不使用循环的情况下将一列添加到对另一列的数据进行日期时间操作的列表中?

问题描述

我正在尝试使用 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 Dataframes 或 Numpy 数组来做到这一点?

这与上一个问题不同

标签: pythonpandasdataframenumpymatplotlib

解决方案


我简化了你的问题:

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

我认为与此类似,您将能够解决您的问题。


推荐阅读