Python 从另一列中给定数值阈值的筛选器列对
我有一个下面的数据框,在这个数据框中,我需要通过从第三列中选择一对具有最高数值的ID来过滤给定两个不同列中的一对ID的行Python 从另一列中给定数值阈值的筛选器列对,python,pandas,Python,Pandas,我有一个下面的数据框,在这个数据框中,我需要通过从第三列中选择一对具有最高数值的ID来过滤给定两个不同列中的一对ID的行 import pandas as pd data = [ ['11x', '12x', 5.5, 'other_1'], ['11x', '12x', 3.5, 'other_2'], ['10x', '9x', 1.5, 'other_1'], ['10x', '9x', 3.5, 'other_2'], ['1x', '1x',
import pandas as pd
data = [
['11x', '12x', 5.5, 'other_1'],
['11x', '12x', 3.5, 'other_2'],
['10x', '9x', 1.5, 'other_1'],
['10x', '9x', 3.5, 'other_2'],
['1x', '1x', 3.5, 'other_x'],
]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['id1', 'id2', 'to_filter_on', 'other_data'])
df.head()
# output of head
"""
id1 id2 to_filter_on other_data
0 11x 12x 5.5 other_1
1 11x 12x 3.5 other_2
2 10x 9x 1.5 other_1
3 10x 9x 3.5 other_2
4 1x 2x 3.5 other_x
"""
给定ID字段对(id1和id2),我只想选择一对,其中从列到上的\u filter\u的阈值最高。从某种意义上说,我需要一个如下的数据帧:
"""
id1 id2 to_filter_on other_data
0 11x 12x 5.5 other_1
1 10x 9x 3.5 other_2
2 1x 2x 3.5 other_x
"""
请注意,至
上的过滤器中具有较低值的ID对“11x和12x”已被删除,与“10x和9x”对相同
非常感谢您的指点和帮助。使用groupby
和idxmax
获取最高“to\u filter\u on”值的索引,然后使用该值索引df
:
df.iloc[df.groupby(['id1', 'id2'], sort=False)['to_filter_on'].idxmax()]
id1 id2 to_filter_on other_data
0 11x 12x 5.5 other_1
3 10x 9x 3.5 other_2
4 1x 1x 3.5 other_x
或者,通过排序和删除重复项来避免使用groupby
:
(df.sort_values(['id1', 'id2', 'to_filter_on'])
.drop_duplicates(['id1', 'id2'], keep='last')
.sort_index())
id1 id2 to_filter_on other_data
0 11x 12x 5.5 other_1
3 10x 9x 3.5 other_2
4 1x 1x 3.5 other_x
如果要保留所有具有相同(最大)值的行,请在
上进行筛选:
s = df.groupby(['id1','id2'])['to_filter_on'].transform('max')
df[df.to_filter_on.eq(s)]
给出:
id1 id2 to_filter_on other_data
0 11x 12x 5.5 other_1
3 10x 9x 3.5 other_2
4 1x 1x 3.5 other_x