带条件的Python选择元组

2024-04-29 07:54:58 发布

您现在位置:Python中文网/ 问答频道 /正文

   module_category    component_category    year_month_sale    year_month_repair 
0              M6                P16          200709            200904   
1              M2                P30          200709            200908   
2              M1                P12          200610            200802   
3              M1                P30          200605            200707   
4              M3                P06          200708            200712

我有一个这样的数据帧。我想问一下,我如何选择或创建一个子集的dataframe与year_month_repair >= 200802只有这样的结果将如下所示?你知道吗

module_category    component_category    year_month_sale    year_month_repair 
0              M6                P16          200709            200904   
1              M2                P30          200709            200908   
2              M1                P12          200610            200802

Tags: saleyearcomponentm3modulerepaircategorymonth
2条回答

尝试.loc[]方法:

df.loc[df.year_month_repair >= '200802']

其中df是您的数据帧

Pythons filter()非常适合:

condition = lambda x: x[3] >= 200802
filteredDataframe = filter(condition, dataframe)

我认为这个代码块是不言自明的:

  • 创建一个带有lambda的匿名函数来应用于每个元组
  • 筛选器应用该函数并返回所有返回true的元组

相关问题 更多 >