首页 > 解决方案 > Pandas DataFrame:如何根据特定列的值巧妙地选择数据?

问题描述

对于 DataFrame,我想根据某些列的值选择行,例如对于数据框:

import pandas as pd

d = {'category': ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c'],
     'colour': ['red', 'blue', 'green', 'orange', 'red', 'blue', 'green', 'orange', 'red', 'blue', 'green', 'orange'],
     'amount': [28.1, 5.6, 43.6, 13.3, 4.1, 27.6, 19.7, 37.5, 26.7, 73.7, 94.4, 77.5],
     'scalar': [3.4, 2.8, 3.4, 1.7, 2.2, 0.8, 1.9, 0.3, 2.4, 0.2, 0.5, 1.5]}
df = pd.DataFrame(d)

结果是:

   category  colour  amount  scalar
0         a     red    28.1     3.4
1         a    blue     5.6     2.8
2         a   green    43.6     3.4
3         a  orange    13.3     1.7
4         b     red     4.1     2.2
5         b    blue    27.6     0.8
6         b   green    19.7     1.9
7         b  orange    37.5     0.3
8         c     red    26.7     2.4
9         c    blue    73.7     0.2
10        c   green    94.4     0.5
11        c  orange    77.5     1.5

要根据我一直在使用的 avalue中的 a选择行,例如:columndf[df[column]==value]

df[df['category']=='b']
  category  colour  amount  scalar
4        b     red     4.1     2.2
5        b    blue    27.6     0.8
6        b   green    19.7     1.9
7        b  orange    37.5     0.3

这是我工作中非常常见的操作,因此是否有某种函数可以在 a 中执行此操作,而不那么混乱(特别是因为column并且value它们本身可以是更长的单词或计算)。

我想这将是这样的形式,df.mask_for(column, value)例如:

df.mask_for('category', 'b')
  category  colour  amount  scalar
4        b     red     4.1     2.2
5        b    blue    27.6     0.8
6        b   green    19.7     1.9
7        b  orange    37.5     0.3

pandas.DataFrame.where()并且pandas.DataFrame.mask()似乎没有实现这一点。

如果它始终与您引用的列相同,则可以将其设置为索引并使用.loc,例如:

df.set_index('category').loc['b',:]
          colour  amount  scalar
category                        
b            red     4.1     2.2
b           blue    27.6     0.8
b          green    19.7     1.9
b         orange    37.5     0.3

但是,如果您在许多不同的列上执行此操作,或者使用其他东西作为索引,那么必须一直设置/重置索引似乎有点笨拙。一般情况下是否有类似的情况?

谢谢!

标签: pythonpython-3.xpandas

解决方案


您可以使用查询功能作为替代方案。

df.query('"category" == "b"')

您还可以编写自己的函数,以便以后节省击键。

def mask_for(df,column,value):
    return(df.loc[df[column]==value])

mask_for(df,'category','b')

推荐阅读