2015-02-11 60 views
1

我才發現,我不能分配是這樣的:同時列分配

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' 

我錯過了什麼嗎?

回答

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 
1

那些看起來像dictionaries所以有官方文檔閱讀。

您可以爲單個鍵分配一些值。關鍵必須是唯一且可散列的(這就是爲什麼字典工作得如此之快並且基本上是python的中堅力量)。列表是可變對象,不能被散列。

看看this甚至this問題。