gpt4 book ai didi

python - Pandas:使用 iterrows() 和 pd.Series 将值附加到系列

转载 作者:行者123 更新时间:2023-11-28 18:09:42 24 4
gpt4 key购买 nike

我的输入数据是这样的:

   cat  start               target
0 1 2016-09-01 00:00:00 4.370279
1 1 2016-09-01 00:00:00 1.367778
2 1 2016-09-01 00:00:00 0.385834

我想构建一个系列,使用“开始”作为开始日期,使用“目标”作为系列值。 iterrows() 正在为“imp”提取正确的值,但是当附加到 time_series 时,只有第一个值会传递到所有系列点。 "data=imp"每次都拉第0行是什么原因?

t0 = model_input_test['start'][0] # t0 = 2016-09-01 00:00:00
num_ts = len(model_input_test.index) # num_ts = 1348
time_series = []
for i, row in model_input_test.iterrows():
imp = row.loc['target']
print(imp)
index = pd.DatetimeIndex(start=t0, freq='H', periods=num_ts)
time_series.append(pd.Series(data=imp, index=index))

A screenshot can be seen here .

系列“time_series”应该是这样的:

2016-09-01 00:00:00    4.370279
2016-09-01 01:00:00 1.367778
2016-09-01 02:00:00 0.385834

但最终看起来像这样:

2016-09-01 00:00:00    4.370279
2016-09-01 01:00:00 4.370279
2016-09-01 02:00:00 4.370279

我在 Sagemaker 上使用 Jupyter conda_python3。

最佳答案

使用数据帧时,通常有更好的方法来执行任务然后遍历数据帧。例如,在您的情况下,您可以像这样创建系列:

time_series = (df.set_index(pd.date_range(pd.to_datetime(df.start).iloc[0],
periods = len(df), freq='H')))['target']


>>> time_series
2016-09-01 00:00:00 4.370279
2016-09-01 01:00:00 1.367778
2016-09-01 02:00:00 0.385834
Freq: H, Name: target, dtype: float64
>>> type(time_series)
<class 'pandas.core.series.Series'>

本质上,这表示:“将索引设置为从您的第一个日期开始每小时递增的日期范围,然后获取 target 列”

关于python - Pandas:使用 iterrows() 和 pd.Series 将值附加到系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51483774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com