簡體   English   中英

在dataframe python中按時間步長開始添加一個值

[英]add one value in the beginning by timestep in dataframe python

我有一個數據框,如下所示,

  df =
   index                value
2014-05-21 10:00:00      13.0
2014-05-21 10:30:00       8.0
2014-05-21 11:00:00       9.0
2014-05-21 11:30:00       7.0
2014-05-21 12:00:00       2.0
....

我如何在開始時添加一個新值2

    df =
   index                value
2014-05-21 09:30:00       2.0   <- new value with new index automatically
2014-05-21 10:00:00      13.0     calculated ( 10 o'clock - 30min(timestep))
2014-05-21 10:30:00       8.0
2014-05-21 11:00:00       9.0
2014-05-21 11:30:00       7.0
2014-05-21 12:00:00       2.0  

type(df.index) = pandas.core.indexes.datetimes.DatetimeIndex

我想在第一個索引中添加值,並且datetime將通過時間步長自動計算(在這種情況下為30分鍾),有沒有更好的方法呢?

提前致謝 !

選項1

df.loc[df.index[0] - pd.offsets.Minute(30), 'value'] = 2
df = df.sort_index()

df

                     value
index                     
2014-05-21 09:30:00    2.0
2014-05-21 10:00:00   13.0
2014-05-21 10:30:00    8.0
2014-05-21 11:00:00    9.0
2014-05-21 11:30:00    7.0
2014-05-21 12:00:00    2.0

選項2

設置索引的頻率,以便您可以自然減少。
這是@root HERE的回答

from pandas.tseries.frequencies import to_offset

df.index.freq = to_offset(df.index.inferred_freq)
df.combine_first(pd.DataFrame(dict(value=[2]), [df.index[0] - 1]))

                     value
index                     
2014-05-21 09:30:00    2.0
2014-05-21 10:00:00   13.0
2014-05-21 10:30:00    8.0
2014-05-21 11:00:00    9.0
2014-05-21 11:30:00    7.0
2014-05-21 12:00:00    2.0

您也可以將reindex與索引append

df.reindex(pd.Index(['2014-05-21 09:30:00']).append(df.index),fill_value=2)
Out[116]: 
                     value
2014-05-21 09:30:00    2.0
2014-05-21 10:00:00   13.0
2014-05-21 10:30:00    8.0
2014-05-21 11:00:00    9.0
2014-05-21 11:30:00    7.0
2014-05-21 12:00:00    2.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM