How to broadcast a scalar to a filtered column in a pandas dataframe

pandas, python

Solution

First choose the column, then filter:

df1.loc[df1['A'] > 2, 'C'] = "R"

   A  B  C
0  1  w  H
1  2  x  H
2  3  y  R
3  4  z  R

Problem

I wish to broadcast the results of an expression to the a dataframe, but not to the entire column, just to a filtered subset. A simplification below: ``` In [6]: df1 = DataFrame({"A":[1, 2, 3, 4], "B":["w", "x", "y", "z"], "C":(numpy. zeros((4), dtype='S1'))}) In [7]: df1 Out[7]: A B C 0 1 w 1 2 x 2 3 y 3 4 z ``` So A and B contain my existing data and column C is prepared to enter my results into. So I can broadcast to the entire column as below: ``` In [9]: df1['C'] = 'H' In [10]: df1 Out[10]: A B C 0 1 w H 1 2 x H 2 3 y H 3 4 z H ``` But if I try and broadcast (in this example, the letter "R") to a filtered subset: ``` In [14]: (df1[df1['A'] > 2])['C'] Out[14]: 2 H 3 H Name: C ``` (just to prove the filtering works) so now I try and assign "R" to this subset.. ``` In [12]: (df1[df1['A'] > 2])['C'] = "R" In [13]: df1 Out[13]: A B C 0 1 w H 1 2 x H 2 3 y H 3 4 z H ``` But my values remain unchanged :( (though interestingly I do not receive an error!?) Please can anyone suggest a way I can achieve this? Many thanks,

Original source