1

Here is a sample code:

>>> import pandas as pd
>>> df = pd.DataFrame([[1, 2, 3, 4],
...                    [5, 6, 7, 8],
...                    [9, 10, 11, 12],
...                    [13, 14, 15, 16]], columns=['a', 'b', 'c', 'd'])
>>> s = pd.Series([True, False, False], index=['a', 'b', 'c'])
>>> df.loc[0, ['a', 'b']][s] = 100
>>> df
    a   b   c   d
0   1   2   3   4
1   5   6   7   8
2   9  10  11  12
3  13  14  15  16

As you can see I was unable to assign 100 to the (0, 'a') element of df. What went wrong?

Sara
  • 245
  • 4
  • 11

1 Answers1

1

First create Series by same length and same values like df.columns with filling False for not matched values and then pass instead ['a','b']:

s = s.reindex(df.columns, fill_value=False)

df.loc[0, s] = 100
print (df)
     a   b   c   d
0  100   2   3   4
1    5   6   7   8
2    9  10  11  12
3   13  14  15  16

Details:

print (s)
a     True
b    False
c    False
d    False
dtype: bool
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252