猿问

查找与另一个数据框中的列具有相同的非唯一列值的数据框行

我有两个数据框- OK_df 和 Not_OK_df :


OK_df = pd.DataFrame({'type_id' : [1,2,3,3], 'count' : [2,7,2,5], 'unique_id' : ['1|2','2|7','3|2','3|5'], 'status' : ['OK','OK','OK','OK']})

Not_OK_df = pd.DataFrame({'type_id' : [1,3,5,6,3,3,3,1], 'count' : [1,1,1,1,3,4,6,3], 'col3' : [1,5,7,3,4,7,2,2], 'unique_id' : ['1|1','3|1','5|1','6|1','3|3','3|4','3|6','1|3'], 'status' : ['Not_OK','Not_OK','Not_OK','Not_OK','Not_OK','Not_OK','Not_OK','Not_OK']})

好的_df:


       type_id  count unique_id status

0        1      2       1|2     OK

1        2      7       2|7     OK

2        3      2       3|2     OK

3        3      5       3|5     OK

Not_OK_df:


  type_id  count  col3 unique_id  status

0        1      1     1       1|1  Not_OK

1        3      1     5       3|1  Not_OK

2        5      1     7       5|1  Not_OK

3        6      1     3       6|1  Not_OK

4        3      3     4       3|3  Not_OK

5        3      4     7       3|4  Not_OK

6        3      6     2       3|6  Not_OK

7        1      3     2       1|3  Not_OK

在哪里,


type_id :对应类型的非唯一 ID。


count :从第一次看到 type_id 开始的计数。


unique_id :type_id 和 count 的组合:'type_id|count'


col3 :另一列。


状态:有值 - OK 或 Not_OK


对于 Ok_df 中的一行,Not_OK_df 中至少有一行具有相同的 type_id,其计数值小于 OK_df 行的计数值。


我想找到满足上述条件的 Not_OK_df 行,即


Not_OK_df['type_id'] == OK_df['type_id'] & Not_OK_df['count'] < OK_df['count']

我尝试直接使用上述条件,但出现以下错误:

Reindexing only valid with uniquely valued Index objects


我无法将匹配的 type_id 设置为索引来检索行,因为 type_id 不是唯一的。我不能使用 unique_id 作为索引来检索,因为它对两个数据帧都是唯一的。

预期的输出是:


   type_id  count  col3 unique_id  status

0        1      1     1       1|1  Not_OK

1        3      1     5       3|1  Not_OK

2        3      3     4       3|3  Not_OK

3        3      4     7       3|4  Not_OK


注意:它不包含具有 unique_id 的行:['3|6','1|3'] 因为 OK_df 中没有具有OK_df['count'] > not_OK_df['count'].


如何检索所需的行。提前致谢。


MMTTMM
浏览 98回答 1
1回答

qq_笑_17

如果我对您的理解正确,您的选择标准如下:来自的行必须与中的行Not_ok_df相同type_idok_df同一行必须具有小于相同行的count最大值counttype_idok_dfcount首先为每个 unique的最大值创建一个字典type_id。max_counts&nbsp;=OK_df.groupby('type_id').max()['count'].to_dict()然后检查是否每一行都Not_ok_df满足您的条件Not_OK_df[&nbsp; &nbsp; Not_OK_df.apply(&nbsp; &nbsp; &nbsp; &nbsp; lambda not_ok_row: max_counts[not_ok_row['type_id']] > not_ok_row['count'] #returns True if there exists a larger count in ok_df with the same type_id&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if not_ok_row['type_id'] in max_counts else False, #checks to see if your Not_ok_df row's type_id exists in ok_df&nbsp; &nbsp; &nbsp; &nbsp; axis=1&nbsp; &nbsp; )]
随时随地看视频慕课网APP

相关分类

Python
我要回答