Assign to a subset of a column using method chaining in Pandas

Viewed 1065

I would like to use the modern way of Pandas method chaining to assign values to a subset of a column.

Let's say I have the following dataframe

df = pd.DataFrame({'a': [1, 0, 0, 1]})

   a
0  1
1  0
2  0
3  1

I would like to achieve the equivalent of

df.loc[df.a == 1, 'a'] = 2

with something like

df.query('a == 1').assign(a=2)

However, the above creates a subset dataframe and does not modify the whole dataframe. Is that somehow possible to achieve?

2 Answers

The query method, as its name indicates, is designed for querying a dataframe, not for setting values.

As such, loc is entirely appropriate, noting you can assign to a series via a string:

df.loc[df.a == 1, 'a'] = 2

More idiomatic may be to use pd.Series.mask, which you can even use in place:

df['a'].mask(df['a'] == 1, 2, inplace=True)

You should view "method chaining" as a means to an end rather than a requirement or objective in its own right. If you are set on using method chaining, you can use pd.DataFrame.assign:

df = df.assign(a=df['a'].mask(df['a'] == 1, 2))

As an isolated operation, I find this less readable. But you may find it useful with multiple linked operations via method chaining.

You can assign the value using the following code

df[df['a']==1]['a']=2
Related