我正在尝试使用Pandas的where
方法,但我坚持了一个错误。这是一个非常小的例子。
提供文件
Chamber,Treatment
1,Sem palha
1,Sem palha
1,Sem palha
2,Sem palha
2,Sem palha
当我跑步时
import pandas
sample = pandas.read_csv('sample.csv')
sample.where(sample['Chamber'] == 1)
我得到
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-62-96ed02cb41da> in <module>()
----> 1 sample.where(sample['Chamber'] == 1)
/usr/lib/python3.4/site-packages/pandas/core/generic.py in where(self, cond, other, inplace, axis, level, try_cast, raise_on_error)
3346 new_data = self._data.where(other=other, cond=cond, align=axis is None,
3347 raise_on_error=raise_on_error,
-> 3348 try_cast=try_cast)
3349
3350 return self._constructor(new_data).__finalize__(self)
/usr/lib/python3.4/site-packages/pandas/core/internals.py in where(self, **kwargs)
2434
2435 def where(self, **kwargs):
-> 2436 return self.apply('where', **kwargs)
2437
2438 def eval(self, **kwargs):
/usr/lib/python3.4/site-packages/pandas/core/internals.py in apply(self, f, axes, filter, do_integrity_check, **kwargs)
2416 copy=align_copy)
2417
-> 2418 applied = getattr(b, f)(**kwargs)
2419
2420 if isinstance(applied, list):
/usr/lib/python3.4/site-packages/pandas/core/internals.py in where(self, other, cond, align, raise_on_error, try_cast)
1043 axis = cond.ndim - 1
1044 cond = cond.swapaxes(axis, 0)
-> 1045 mask = np.array([cond[i].all() for i in range(cond.shape[0])],
1046 dtype=bool)
1047
/usr/lib/python3.4/site-packages/pandas/core/internals.py in <listcomp>(.0)
1043 axis = cond.ndim - 1
1044 cond = cond.swapaxes(axis, 0)
-> 1045 mask = np.array([cond[i].all() for i in range(cond.shape[0])],
1046 dtype=bool)
1047
AttributeError: 'float' object has no attribute 'all'
你的语法实际上可以在新版本的熊猫中使用。您可以使用以下命令在 Ubuntu 上升级熊猫
sudo pip install --upgrade pandas
或者如果你使用的是python3,那么
sudo pip3 install --upgrade pandas
正如unutbu在评论中指出的那样,where
似乎是一个"单元格明智"的选择。这些变体按预期工作:
sample[sample["Chamber"] == 1]
和
sample.query("Chamber == 1")