如何通过在熊猫时间序列数据框中搜索数据来添加新列

时间:2019-02-14 14:12:58

标签: python pandas dataframe search

我有一个熊猫时间序列数据框。 它具有30天库存的分钟数据。 我想创建一个新列,说明当天上午6点的股票价格,例如对于1月1日的所有行,我想要一个新列,其价格为1月1日中午;对于1月2日的所有行,我想要一个新列的价格为1月2日,中午,等等。

Existing timeframe:
Date   Time   Last_Price   Date   Time   12amT
1/1/19 08:00  100          1/1/19 08:00  ?
1/1/19 08:01  101          1/1/19 08:01  ?
1/1/19 08:02  100.50       1/1/19 08:02  ?
...
31/1/19 21:00 106         31/1/19 21:00  ?

我使用了这种技巧,但是它非常慢,并且我认为有一种更快更容易的方法。

for lab, row in df.iterrows() :
    t=row["Date"]
    df.loc[lab,"12amT"]=df[(df['Date']==t)&(df['Time']=="12:00")]["Last_Price"].values[0]

2 个答案:

答案 0 :(得分:1)

一种方法是将groupby与pd.Grouper一起使用:

对于熊猫24.1 +

df.groupby(pd.Grouper(freq='D'))[0]\
  .transform(lambda x: x.loc[(x.index.hour == 12) & 
                             (x.index.minute==0)].to_numpy()[0])

大熊猫使用:

 df.groupby(pd.Grouper(freq='D'))[0]\
   .transform(lambda x: x.loc[(x.index.hour == 12) &
                              (x.index.minute==0)].values[0])

MVCE:

df = pd.DataFrame(np.arange(48*60), index=pd.date_range('02-01-2019',periods=(48*60), freq='T'))

df['12amT'] = df.groupby(pd.Grouper(freq='D'))[0].transform(lambda x: x.loc[(x.index.hour == 12)&(x.index.minute==0)].to_numpy()[0])

输出(头):

                    0  12amT
2019-02-01 00:00:00  0    720
2019-02-01 00:01:00  1    720
2019-02-01 00:02:00  2    720
2019-02-01 00:03:00  3    720
2019-02-01 00:04:00  4    720

答案 1 :(得分:0)

我不确定您为什么有两个DateTime列,我以自己的示例进行了演示:

ind = pd.date_range('1/1/2019', '30/1/2019', freq='H')
df = pd.DataFrame({'Last_Price':np.random.random(len(ind)) + 100}, index=ind)

def noon_price(df):
    noon_price = df.loc[df.index.hour == 12, 'Last_Price'].values
    noon_price = noon_price[0] if len(noon_price) > 0 else np.nan
    df['noon_price'] = noon_price
    return df

df.groupby(df.index.day).apply(noon_price).reindex(ind)
默认情况下,

reindex将用其noon_price填充每天的行。

要添加第二天正午价格的列,您可以shift将该列向下排24行,如下所示:

df['T+1'] = df.noon_price.shift(-24)