假设有以下数据:
id | value |
---|---|
1 | 4 |
1 | 6 |
2 | 6 |
2 | 7 |
3 | 9 |
3 | 5 |
我们想要按照id分组,然后查看每组的value列是否是递增的。可以使用pandas库中的groupby()和apply()方法实现:
import pandas as pd
data = {
'id': [1, 1, 2, 2, 3, 3],
'value': [4, 6, 6, 7, 9, 5]
}
df = pd.DataFrame(data)
def check_ascending(x):
"""
用于检查一组数据是否是递增的函数。
"""
return all(x[i] <= x[i+1] for i in range(len(x)-1))
result = df.groupby('id')['value'].apply(check_ascending)
print(result)
输出结果为:
id
1 True
2 True
3 False
Name: value, dtype: bool
这表明id为1和2的组都是递增的,而id为3的组不是递增的。