1

I just found that I can't assign like this:

df[['a','b','c']] = 'total'

or

df.loc[:, ['a','b','c']] = 'total

However, I can do

df['a'] = 'total'
df['b'] = 'total'
df['c'] = 'total'

or

df['a'] = df['b'] = df['c'] = 'total'

Am I missing something?

dmvianna
  • 15,088
  • 18
  • 77
  • 106

2 Answers2

1

Those look like dictionaries so have a read on the official documentation.

You can assign a single key some value. The key must be unique and hashable (that's why dicts work so fast and are basically the backbone of python). Lists are mutable objects and can't be hashed.

Take a look at this or even this questions.

Community
  • 1
  • 1
ljetibo
  • 3,048
  • 19
  • 25
1

You can use ix to set multiple columns at the same time without problem:

In [8]:

df = pd.DataFrame({'a':np.random.randn(5), 'b':np.random.randn(5), 'c':np.random.randn(5)})
df
Out[8]:
          a         b         c
0  0.623686  0.875752  1.027399
1 -0.806096  0.349891  0.290276
2  0.750623  0.704666 -1.401591
3 -0.594068 -1.148006  0.373021
4 -1.060019 -0.325563 -0.536769

In [9]:

df.ix[:,['a','b','c']] = 'total'
df
Out[9]:
       a      b      c
0  total  total  total
1  total  total  total
2  total  total  total
3  total  total  total
4  total  total  total
EdChum
  • 376,765
  • 198
  • 813
  • 562