python - 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选择行,例如:column
df[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
但是,如果您在许多不同的列上执行此操作,或者使用其他东西作为索引,那么必须一直设置/重置索引似乎有点笨拙。一般情况下是否有类似的情况?
谢谢!
解决方案
您可以使用查询功能作为替代方案。
df.query('"category" == "b"')
您还可以编写自己的函数,以便以后节省击键。
def mask_for(df,column,value):
return(df.loc[df[column]==value])
mask_for(df,'category','b')
推荐阅读
- ruby-on-rails - 章鱼rails gem中的模型特定数据库分片
- python - 在 Flask 应用程序中的 IntegrityError 之后,数据库中的 ID 不按顺序排列
- .net - 我想安装一些像“microsoft.aspnet.webapi.cors”这样的nuget包,但有如下错误
- angular - 如何从 iframe 向 Angular 应用程序传递值
- google-sheets - SUMPRODUCT 中的 ArrayFormula 和扩展范围
- javascript - KNEX / SQLite 处理日期
- flutter - 启动应用程序时初始化 CupertinoPicker (flutter)
- latex - 整个文档的字体大小都在减小 - LaTeX
- python - 在 tensorflow 中加载 tiff 图像来抑制警告似乎不起作用?
- android - 我应该独立于 Fragment 的生命周期使用 ViewModelScope 吗?