user3848207
user3848207

Reputation: 4937

Detect Saturday in panda dataframe and modify value in row

I have the panda dataframe in python below.

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

 

I want to detect which row falls on a Saturday based on column Date_YMD. Find out the volume value on this Saturday and replace it with double the value. For the table above, it should be 14224 belonging to row with Date_YMD 20200926.

The final dataframe should look something like this;

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   28448.0  

I am using python 3.8.

Upvotes: 2

Views: 32

Answers (1)

jezrael
jezrael

Reputation: 862921

Convert column to datetimes and then multiple values by selected compared with Series.dt.dayofweek and DataFrame.loc:

df['Date_YMD'] = pd.to_datetime(df['Date_YMD'], format='%Y%m%d')

df.loc[df['Date_YMD'].dt.dayofweek.eq(5), 'volume'] *= 2
print (df)
  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  62295.0
4  bottle_a   AX80 2020-09-26  12880.0  13000.00  28448.0

Upvotes: 2

Related Questions