Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Re-assigning values to a 'block' of a Data frame

Probably a trivial problem, but I need to understand what's going on here (and how to fix it).

Suppose I have a dataframe with columns 'a' and 'b', as follows:

f = pandas.DataFrame({'a':[1,2,3,4,5], 'b':[10,20,30,40,50]})

Now for every element of 'a' that is 3 or less, I want to divide the corresponding elements of 'b' by 10.

f[f['a']<=3]['b'] = (f[f['a']<=3]['b'])/10

So that the values in column 'b' should now be [1,2,3,40,50].

But I find that column 'b' remains unchanged! What gives?

like image 250
user2383521 Avatar asked Mar 23 '23 23:03

user2383521


1 Answers

I think you are trying to assign values to a copy rather than a view (f[f['a']<=3]['b'] is a copy), see Returning a view versus a copy.

However, you can reorder this and it'll work be a view:

In [11]: f['b'][f['a']<=3] = (f[f['a']<=3]['b'])/10

In [12]: f
Out[12]:
   a   b
0  1   1
1  2   2
2  3   3
3  4  40
4  5  50
like image 169
Andy Hayden Avatar answered Apr 13 '23 08:04

Andy Hayden