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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With