hopieman
hopieman

Reputation: 389

Filter Pandas Data frame

I have this pandas dataframe:

                     open    high     low   close      volume
TimeStamp                                                      
2016-06-23 10:00:00  586.76  594.00  585.54  589.94  478.176973
2016-06-23 11:00:00  589.94  595.49  588.23  592.63  448.689485
2016-06-23 12:00:00  592.63  592.63    1.50  581.13  527.816891
2016-06-23 13:00:00  581.13  586.33  578.58  580.96  728.424757

As you can see one of the values is not ok. So I want to filter it and change it to the mean of the last 5 values

With this

df['avg']=df['low'].rolling(5).mean().shift()

I get this

                      open    high     low   close      volume      avg
TimeStamp                                                               
2016-06-23 10:00:00  586.76  594.00  585.54  589.94  478.176973  573.326
2016-06-23 11:00:00  589.94  595.49  588.23  592.63  448.689485  578.438
2016-06-23 12:00:00  592.63  592.63    1.50  581.13  527.816891  583.202
2016-06-23 13:00:00  581.13  586.33  578.58  580.96  728.424757  467.348

And now I want to give to the low the same value of avg. The filter finds value that has a "variance" bigger than 5.

df.loc[(df['high']/df['low'])>5]['low']


                       open    high  low   close      volume      avg
TimeStamp                                                            
2016-06-23 12:00:00  592.63  592.63  1.5  581.13  527.816891  583.202

But when I try to give the value, it doesn't work..

 df.loc[(df['high']/df['low'])>5]['low']=df.loc[(df['high']/df['low'])>5]['avg']

Can you help me?

Upvotes: 2

Views: 96

Answers (1)

BENY
BENY

Reputation: 323316

pandas' dataframe is base on index, so what you need is just

df.loc[(df['high']/df['low'])>5,'low']=df.avg
df
Out[1331]: 
     open    high     low   close      volume     avg
0  586.76  594.00  585.54  589.94  478.176973     NaN
1  589.94  595.49  588.23  592.63  448.689485  585.54
2  592.63  592.63  588.23  581.13  527.816891  588.23
3  581.13  586.33  578.58  580.96  728.424757    1.50

Upvotes: 2

Related Questions