0

I have the following dataframe:

Time           00:00  ...     23:00
Date                  ...          
2022-08-01  0.000000  ...  0.249884
2022-08-02  0.177274  ...  0.846479
2022-08-03  0.275984  ...  0.333089
2022-08-04  0.206237  ...  0.295780
2022-08-05  0.138474  ...  0.163897
...

how can I multiply row values depending from the date (index column)? For example - for the range from August 1 to 3 - by 2; for the range from August 4 till the last row in dataframe - by 3. should I follow solutions like here: link to the article on slackoverflow

JanisE
  • 37
  • 1
  • 8

1 Answers1

0

Here is a sample code to multiply the values in a range:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(10,2)),
              columns=["col1", "col2"],
              index=pd.date_range("20221212", periods=10))

Dataframe before change

Now to multiply from 12th to 16th by 2 and the rest of rows by 3:

for col in df.columns.values:
    df.loc['2022-12-12' :'2022-12-16',col] *= 2 
    df.loc['2022-12-17' :'2022-12-21',col] *= 3

Dataframe after changes

Nathan
  • 471
  • 2
  • 12
  • doing print (df['2022-12-08':'2022-12-10']['Date'] *2 ) I get raise KeyError(key) from err KeyError: 'Date' (there are data for the indicated dates) – JanisE Dec 12 '22 at 15:45
  • print (df.index.name) gives Date; print(df.columns.tolist()) gives ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'] – JanisE Dec 12 '22 at 15:48
  • To multiply each column, use: for col in df.columns.tolist(): df['2022-12-08' :'2022-12-10'][col]*=2 – Nathan Dec 12 '22 at 20:20
  • following advice I get: Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy for col in df.columns.tolist(): df['2022-12-08' :'2022-12-10'][col]*=2 – JanisE Dec 12 '22 at 22:59
  • I updated the code to avoid the slice warning. – Nathan Dec 13 '22 at 23:12
  • Many thanks! I like Pandas more and more :) – JanisE Dec 15 '22 at 08:12