Vijay Sharma
Vijay Sharma

Reputation: 31

Why setting the value of a column in pandas is not working>

[enter image description here][1]I have a data frame named election and I want to find set the winner column as NaN for rows where the margin is less than 1

![enter image description here][2]

I am doing something like this

too_close = election['margin']<1

election.loc[too_close, 'winner'] = np.nan # THIS IS WORKING

My question is since election.loc[too_close, 'winner'] and election[too_close].winner both return pandas series. Why setting the column value using latter doesn't work and the former works. I am new to pandas. Here is the data frame's 5 initial values

          state   total      Obama     Romney  winner  voters    turnout     margin
county                                                                             
Adams        PA   41973  35.482334  63.112001  Romney   61156  68.632677  27.629667
Allegheny    PA  614671  56.640219  42.185820   Obama  924351  66.497575  14.454399
Armstrong    PA   28322  30.696985  67.901278  Romney   42147  67.198140  37.204293
Beaver       PA   80015  46.032619  52.637630  Romney  115157  69.483401   6.605012
Bedford      PA   21444  22.057452  76.986570  Romney   32189  66.619031  54.929118

Upvotes: 0

Views: 863

Answers (1)

Josh Friedlander
Josh Friedlander

Reputation: 11657

Pandas separates between getting and setting (ie, changing) methods. Since setting modifies your original dataframe, Pandas wants to be more cautious about how you do it. loc is the official way to do this. Syntax like election[too_close].winner is simply a shortcut (or "sugar") for getting, but doesn't allow you to set.

Upvotes: 1

Related Questions