Python 比较后,将当前行值分配给panda dataframe的前一行
下面是python中的panda数据帧Python 比较后,将当前行值分配给panda dataframe的前一行,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,下面是python中的panda数据帧 full_name serial Date_YMD prc1 prc2 volume bottle_a AX80 20200922 12874.50 12927.75 61023.0 bottle_a AX80 20200923 12878.50 12926.75 61023.0 bottle_a AX80 20200924 12872.50 12928.75
full_name serial Date_YMD prc1 prc2 volume
bottle_a AX80 20200922 12874.50 12927.75 61023.0
bottle_a AX80 20200923 12878.50 12926.75 61023.0
bottle_a AX80 20200924 12872.50 12928.75 61023.0
bottle_a AX80 20200925 12885.50 12984.25 62295.0
bottle_a AX80 20200926 12880.00 13000.00 14224.0
首先,我想根据列Date\u YMD
检测哪一行属于星期六。然后,找出本周六的音量值,如果前一行的音量值大于当前行的音量值,则将该值分配给前一行的音量
最后一个熊猫框架如上图所示
full_name serial Date_YMD prc1 prc2 volume
bottle_a AX80 20200922 12874.50 12927.75 61023.0
bottle_a AX80 20200923 12878.50 12926.75 61023.0
bottle_a AX80 20200924 12872.50 12928.75 61023.0
bottle_a AX80 20200925 12885.50 12984.25 14224.0
bottle_a AX80 20200926 12880.00 13000.00 14224.0
星期六卷可通过以下代码获得:
df['Date_YMD'] = pd.to_datetime(df['Date_YMD'], format='%Y%m%d')
sat_volume = df.loc[df['Date_YMD'].dt.dayofweek.eq(5), 'volume']
问题是,在比较这些值之后,如何将此sat\u卷
相应地分配给前一行的卷
我正在使用python 3.8让我们创建布尔掩码m1
和m2
,然后使用这些掩码的布尔索引填充卷
列,其中满足了m1
和m2
指定的条件:
m1 = df['volume'] > df['volume'].shift(-1)
m2 = df['Date_YMD'].shift(-1).dt.weekday.eq(5)
df.loc[m1 & m2, 'volume'] = df['volume'].shift(-1)
full_name serial Date_YMD prc1 prc2 volume
0 bottle_a AX80 2020-09-22 12874.5 12927.75 61023.0
1 bottle_a AX80 2020-09-23 12878.5 12926.75 61023.0
2 bottle_a AX80 2020-09-24 12872.5 12928.75 61023.0
3 bottle_a AX80 2020-09-25 12885.5 12984.25 14224.0
4 bottle_a AX80 2020-09-26 12880.0 13000.00 14224.0