Home > other >  copy values in a dataframe according to specific filter
copy values in a dataframe according to specific filter

Time:01-31

I have this dataframe:

time open close giorno ora
2021-09-01 08:00:00 152.03 152.31 1 8
2021-09-01 09:00:00 152.21 152.28 1 9
2021-09-01 10:00:00 152.27 153.89 1 10
2021-09-01 11:00:00 153.9 154.31 1 11
2021-09-01 12:00:00 154.32 154.28 1 12
2021-09-01 13:00:00 154.28 153.44 1 13
2021-09-02 08:00:00 152.98 153.27 2 8
2021-09-02 09:00:00 153.27 153.56 2 9
2021-09-02 10:00:00 153.54 153.94 2 10
2021-09-02 11:00:00 153.94 153.83 2 11
2021-09-02 12:00:00 153.84 153.36 2 12
2021-09-02 13:00:00 153.36 153.08 2 13
2021-09-03 08:00:00 153.67 153.96 3 8
2021-09-03 09:00:00 153.68 153.92 3 9
2021-09-03 10:00:00 153.96 154.11 3 10
2021-09-03 11:00:00 154.11 153.67 3 11
2021-09-03 12:00:00 153.66 153.76 3 12
2021-09-03 13:00:00 153.77 153.63 3 13
2021-09-07 08:00:00 154.07 154.46 7 8
2021-09-07 09:00:00 154.38 154.72 7 9
2021-09-07 10:00:00 154.72 155.49 7 10
2021-09-07 11:00:00 155.47 155.8 7 11
2021-09-07 12:00:00 155.79 155.59 7 12
2021-09-07 13:00:00 155.58 156.87 7 13

I want to copy the value in this way:

if  "ora"=10 then copy "open" cell in all the rows in the same day (column "giorno") in a new column

For exemple about the time 2021-09-01 10:00:00 i want to copy the value 152.27 and past to a new column corrisponding to the rows of giorno=1

time open close giorno ora newColumn
2021-09-01 08:00:00 152.03 152.31 1 8 152.27
2021-09-01 09:00:00 152.21 152.28 1 9 152.27
2021-09-01 10:00:00 152.27 153.89 1 10 152.27
2021-09-01 11:00:00 153.9 154.31 1 11 152.27
2021-09-01 12:00:00 154.32 154.28 1 12 152.27
2021-09-01 13:00:00 154.28 153.44 1 13 152.27

CodePudding user response:

You can use apply with a lambda function to achieve this.

df['newColumn'] = df.apply(lambda x: float(df['open'][(df['giorno'] == x['giorno']) & (df['ora'] == 10)]), axis=1)

full code:

import pandas as pd

df = pd.read_html('https://stackoverflow.com/questions/70914561/copy-values-in-a-dataframe-according-to-specific-filter')[0]
df['newColumn'] = df.apply(lambda x: float(df['open'][(df['giorno'] == x['giorno']) & (df['ora'] == 10)]), axis=1)
df[df['giorno'] == 1]

output:

    time                open    close   giorno  ora newColumn
0   2021-09-01 08:00:00 152.03  152.31  1       8   152.27
1   2021-09-01 09:00:00 152.21  152.28  1       9   152.27
2   2021-09-01 10:00:00 152.27  153.89  1       10  152.27
3   2021-09-01 11:00:00 153.90  154.31  1       11  152.27
4   2021-09-01 12:00:00 154.32  154.28  1       12  152.27
5   2021-09-01 13:00:00 154.28  153.44  1       13  152.27
  •  Tags:  
  • Related