本文介绍了 pandas :迭代过滤DataFrame的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 DataFrame ,所以

df = pd.DataFrame([['x', 1, 2], ['x', 1, 3], ['y', 2, 2]], 
                  columns=['a', 'b', 'c'])

选择所有行,其中 c == 2 a =='x',我可以做一些像

To select all rows where c == 2 and a == 'x', I could do something like,

df[(df['a'] == 'x') & (df['c'] == 2)]

或者我可以通过临时变量进行迭代细化,

Or I could iterative refine by making temporary variables,

df1 = df[df['a'] == 'x']
df2 = df1[df1['c'] == 2]

有没有办法迭代细化行? p>

Is there a way to iterative refine on rows?

(
  df
  .refine(lambda row: row['a'] == 'x')     # this method doesn't exist
  .refine(lambda row: row['c'] == 2)
)


推荐答案

虽然这不是现在的解决方案,在pandas版本0.13中,您可以做到

While this isn't a solution for now, in pandas version 0.13 you'll be able to do

df.query('a == "x"').query('c == 2')

实现你想要的。

你也可以做

df['a == "x"']['c == 2']

df['a == "x" and c == 2']

ith

df[(df.a == 'x') & (df.c == 2)]

直到0.13?

这篇关于 pandas :迭代过滤DataFrame的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 05:46