Python 在条件为真的情况下,用序列中的元素替换列,对数据帧进行布尔索引

Python 在条件为真的情况下,用序列中的元素替换列,对数据帧进行布尔索引,python,pandas,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 例如,我想用长度为df.shape[0]的系列s的对应元素替换>0的

我有一个数据帧:

>>>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 
例如,我想用长度为df.shape[0]的系列
s
的对应元素替换>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
但是我没有得到结果,而是得到了一个
轴缺失的错误。如何在上面的语句中指定轴

错误消息:

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

解决办法显而易见:

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

你只需要否定这个条件。有时候,当你在屏幕前坐太久的时候,你很容易失明

好像是虫子。我认为是在内部转换为
,其中
。因此您可以只使用
df.where(df>0,s,axis=0)
。@jezrael:不幸的是,这不起作用,因为s在不起作用的地方被替换(df>0)。正如我所写的,在这个例子中这并不是问题,但我真正的标准要复杂得多,而反过来制定标准确实增加了一层复杂性。
>>>df.where(~(df>0),s)