这是一个使用Python的pandas库来按两列分组行并按比较筛选值的示例代码:
import pandas as pd
# 创建示例数据
data = {
'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'two', 'two', 'one', 'one', 'two'],
'C': [1, 2, 3, 4, 5, 6, 7, 8],
'D': [10, 20, 30, 40, 50, 60, 70, 80]
}
df = pd.DataFrame(data)
# 按两列分组行并按比较筛选值
filtered_df = df.groupby(['A', 'B']).filter(lambda x: (x['C'] > 3).any())
print(filtered_df)
输出结果:
A B C D
1 bar one 2 20
3 bar two 4 40
4 foo two 5 50
5 bar one 6 60
6 foo one 7 70
7 foo two 8 80
解释:以上示例代码首先创建了一个包含'A'、'B'、'C'和'D'列的DataFrame。然后使用groupby()
方法按照'A'和'B'列进行分组,接着使用filter()
方法筛选出满足条件(x['C'] > 3).any()
的分组。最后输出筛选后的DataFrame。
在本示例中,筛选条件是至少有一个'C'列的值大于3。根据这个条件,分组'foo'和'one'的行被保留了下来,而其他分组被过滤掉了。