我试着在一个.locAPI中使用:

df = pd.DataFrame(dict(age=[99, 33, 33, 22, 33, 44],
                       aa2=[199, 3, 43, 22, 23, 54],
                       nom=['a', 'z', 'f', 'b', 'p', 'a'],))
df.loc[df.age>30]
#    aa2  age nom
# 0  199   99   a
# 1    3   33   z
# 2   43   33   f
# 4   23   33   p
# 5   54   44   a

但我有个错误:
df.loc[df.age>30 and (df.age > df.aa2)]
# ---------------------------------------------------------------------------
# ValueError                                Traceback (most recent call last)
# <ipython-input-13-930dff789922> in <module>()
# ----> 1 df.loc[df.age>30 and (df.age > df.aa2)]
#
# /site-packages/pandas/core/generic.pyc in __nonzero__(self)
#     729         raise ValueError("The truth value of a {0} is ambiguous. "
#     730                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
# --> 731                          .format(self.__class__.__name__))
#     732
#     733     __bool__ = __nonzero__
#
# ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

现在我这样做;(::
df.loc[df.age>30].loc[(df.age > df.aa2)]

#    aa2  age nom
# 1    3   33   z
# 4   23   33   p

最佳答案

>>> df.loc[(df.age>30) & (df.age > df.aa2)]
   aa2  age nom
1    3   33   z
4   23   33   p

关于python - 如何在Pandas loc API中使用*和*,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39129224/

10-09 13:49