python - 查找与另一个数据框中的列具有相同非唯一列值的数据框的行
问题描述
我有两个数据框- 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 :另一列。
status : 有值 - 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']
.
如何检索所需的行。提前致谢。
解决方案
如果我理解正确,您的选择标准如下:
- from 的行
Not_ok_df
必须与type_id
in 的行相同ok_df
- 同一行必须具有
count
小于相同count
行type_id
中的最大值ok_df
count
首先为每个 unique的最大值创建一个字典type_id
。
max_counts =OK_df.groupby('type_id').max()['count'].to_dict()
然后检查是否每一行都Not_ok_df
满足您的条件
Not_OK_df[
Not_OK_df.apply(
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
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
axis=1
)
]