布尔值为pandas中的DataFrame索引,用条件为True的Series元素替换列

时间:2016-03-05 10:53:37

标签: python pandas

我有一个数据框:

>>>df=pd.DataFrame(np.random.randn(3,3))
>>>df
             0         1         2
   0 -0.685692  0.180900  0.652838
   1  0.484584 -0.441004 -1.617281
   2 -0.665110  1.196987 -0.133439 

我想用> 0替换行的所有元素,例如使用长度为s的系列df.shape[0]的相应元素:

>>>s = pd.Series((3,4,5))
>>>s
   0    3
   1    4
   2    5
   dtype: int64

适用于:

>>>df.where(df<=0, s, axis=0)
             0         1         2
   0 -0.685692  3.000000  3.000000
   1  4.000000 -0.441004 -1.617281
   2 -0.665110  5.000000 -0.133439

但我的真实标准非常复杂,所以我想以积极的方式陈述标准(而不是像上面的where声明那样用<=0代替>0来反转标准方式:

>>>df[df>0] = s

但是我得到的错误是axis缺失,而不是结果。如何在上面的语句中指定轴?

错误讯息:

Traceback (most recent call last):
  Python Shell, prompt 97, line 1
  File "/Users/a/anaconda/lib/python2.7/site-packages/pandas/core/frame.py", line 2297, in __setitem__
    self._setitem_frame(key, value)
  File "/Users/a/anaconda/lib/python2.7/site-packages/pandas/core/frame.py", line 2335, in _setitem_frame
    self.where(-key, value, inplace=True)
  File "/Users/a/anaconda/lib/python2.7/site-packages/pandas/core/generic.py", line 3940, in where
    fill_value=np.nan)
  File "/Users/a/anaconda/lib/python2.7/site-packages/pandas/core/frame.py", line 2680, in align
    fill_axis=fill_axis, broadcast_axis=broadcast_axis)
  File "/Users/a/anaconda/lib/python2.7/site-packages/pandas/core/generic.py", line 3784, in align
    fill_axis=fill_axis)
  File "/Users/a/anaconda/lib/python2.7/site-packages/pandas/core/generic.py", line 3870, in _align_series
    raise ValueError('Must specify axis=0 or 1')
ValueError: Must specify axis=0 or 1

1 个答案:

答案 0 :(得分:1)

解决方案显而易见:

>>>df.where(~(df>0),s)

你只需要否定这个条件。有时在屏幕前坐太久时,人们往往会失明!