我想使用一组条件过滤数据帧中的行
首先,创建一个示例数据帧
example = pd.DataFrame({
'Name': ['Joe', 'Alice', 'Steve', 'Jennie','Katie','Vicky','Natalia','Damodardas'],
'Age': [33, 39, 22, 42, 23, 24, 22, 56]})
现在,我需要了解30-40岁年龄组的人。一种方法是按顺序应用年龄条件(见下文)
example = example.loc[example.Age>=30]
example = example.loc[example.Age<40]
print(example)
是否有另一个选项同时应用这两个条件?下面的代码抛出一个错误
example = example.loc[example.Age>=30 and example.Age<40]
print(example)
一种可能的选择是使用介于之间的函数
注意:此函数具有包含的参数(默认值True)
另一种可能是使用查询函数,在您的情况下:
查询是一个非常强大的功能。阅读文档了解更多信息
您的方法是正确的,只需使用“&;”而不是“和”
或者您也可以不使用loc:
在pandas中,不能使用
and
或or
操作:而是使用
&
:相关问题 更多 >
编程相关推荐