同时列分配

时间:2015-02-11 00:32:16

标签: python pandas variable-assignment

我刚发现我不能像这样分配:

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

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

然而,我可以做到

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

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

我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

那些看起来像dictionaries所以请阅读官方文档。

您可以为单个键分配一些值。密钥必须是唯一且可清除的(这就是为什么dicts工作如此之快并且基本上是python的支柱)。列表是可变对象,无法进行哈希处理。

查看this甚至this个问题。

答案 1 :(得分:1)

您可以使用ix同时设置多个列而不会出现问题:

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