簡體   English   中英

如何在 pandas dataframe 中使用連接方法

[英]How to use join method in pandas dataframe

我有這行代碼,它獲取前一天的最后一個值並將其重復添加到新列中的第二天。 工作正常。

df = df.join(df.resample('B', on='Date')['x'].last().rename('xnew'), on=pd.to_datetime((df['Date'] - pd.tseries.offsets.BusinessDay()).dt.date))

現在我需要類似的東西,但我無法讓它工作。
我現在需要“打開”中當天的第一個值,並將該值復制到新列“打開”中的每一行中,每一天
我試過這個但它不起作用:

df = df.join(df.resample('B', on='Date')['Open'].last().rename('opening'), on=pd.to_datetime((df['Date'])))

錯誤:

ValueError: columns overlap but no suffix specified: Index(['opening'], dtype='object')

我怎么能做到這一點?

和:

opening = df.resample('B', on='Date')['Open'].first()

Date
2019-06-20    2927.25
2019-06-21    2932.75
2019-06-24    2942.00
2019-06-25    2925.00
2019-06-26    2902.75
               ...   
2020-06-17    3116.50
2020-06-18    3091.50
2020-06-19    3101.75
2020-06-22    3072.75
2020-06-23    3111.25

..我得到了第一個值,我想要的 output 是

        Date                 Open       opening
1       2020-06-24 07:00:00  3091.50    3111.25  
2       2020-06-24 07:05:00  3092.50    3111.25
3       2020-06-24 07:10:00  3090.25    3111.25
4       2020-06-24 07:15:00  3089.75    3111.25

這是一些示例數據。 對於此示例,現在的日期是從 7:00 到 7:15:

           Time             Open
Date        
2019-06-20 07:00:00 70000   2927.25
2019-06-20 07:05:00 70500   2927.00
2019-06-20 07:10:00 71000   2927.00
2019-06-20 07:15:00 71500   2926.75
2019-06-21 07:00:00 70000   2932.75
2019-06-21 07:05:00 70500   2932.25
2019-06-21 07:10:00 71000   2933.00
2019-06-21 07:15:00 71500   2930.75
2019-06-24 07:00:00 70000   2942.00
2019-06-24 07:05:00 70500   2941.50
2019-06-24 07:10:00 71000   2942.00
2019-06-24 07:15:00 71500   2941.50
2019-06-25 07:00:00 70000   2925.00
2019-06-25 07:05:00 70500   2925.75
2019-06-25 07:10:00 71000   2926.50
2019-06-25 07:15:00 71500   2926.00
2019-06-26 07:00:00 70000   2902.75
2019-06-26 07:05:00 70500   2903.00
2019-06-26 07:10:00 71000   2904.00
2019-06-26 07:15:00 71500   2904.25

我開始使用與您類似的方法resample 我添加的東西是移動所有值,以便每個值都將在第二天作為索引。 然后我可以將此值提供給日期應用的Series.map

這是代碼:

df['opening'] = df.Date.dt.date.map(df.resample('B', on='Date').Open.first().shift())
    Date                Open    opening
0   2019-06-20 07:00:00 2927.25 
1   2019-06-20 07:05:00 2927.0  
2   2019-06-20 07:10:00 2927.0  
3   2019-06-20 07:15:00 2926.75 
4   2019-06-21 07:00:00 2932.75 2927.25
5   2019-06-21 07:05:00 2932.25 2927.25
6   2019-06-21 07:10:00 2933.0  2927.25
7   2019-06-21 07:15:00 2930.75 2927.25
8   2019-06-24 07:00:00 2942.0  2932.75
9   2019-06-24 07:05:00 2941.5  2932.75
10  2019-06-24 07:10:00 2942.0  2932.75
11  2019-06-24 07:15:00 2941.5  2932.75
12  2019-06-25 07:00:00 2925.0  2942.0

當然,第一天會有NaN。

暫無
暫無

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

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