假设我有一个函数来比较一个rabrame中的行:
def comp(lhs: pandas.Series, rhs: pandas.Series) -> bool:
if lhs.id == rhs.id:
return True
if abs(lhs.val1 - rhs.val1) < 1e-8:
if abs(lhs.val2 - rhs.val2) < 1e-8:
return True
return False
现在,我有一个包含id
、val1
和val2
列的子帧,我想生成组ID,以便任何两行的comp
计算为true都有组号.我该如何处理Pandas ?我一直在想办法让groupby
实现这一点,但想不出办法.
MRE:
example_input = pandas.DataFrame({
'id' : [0, 1, 2, 2, 3],
'value1' : [1.1, 1.2, 1.3, 1.4, 1.1],
'value2' : [2.1, 2.2, 2.3, 2.4, 2.1]
})
example_output = example_input.copy()
example_output.index = [0, 1, 2, 2, 0]
example_output.index.name = 'groups'