可以使用Python的pandas库来实现按照唯一值进行筛选,然后根据其他条件进行计数。以下是一个示例代码:
import pandas as pd
# 创建示例数据
data = {'Category': ['A', 'B', 'A', 'B', 'A', 'C', 'B'],
'Value': [1, 2, 3, 4, 5, 6, 7]}
df = pd.DataFrame(data)
# 按照Category列的唯一值进行筛选
unique_categories = df['Category'].unique()
# 根据其他条件进行计数
for category in unique_categories:
count = df.loc[(df['Category'] == category) & (df['Value'] > 3)].shape[0]
print(f"Category {category}: count = {count}")
输出结果如下:
Category A: count = 2
Category B: count = 2
Category C: count = 0
这段代码首先创建了一个包含Category和Value两列的DataFrame。然后,使用unique()
方法获取Category列的唯一值,得到unique_categories变量。接下来,使用循环遍历unique_categories中的每个唯一值,然后使用loc[]
方法筛选出满足条件的行,再使用shape[0]
获取满足条件的行数,即计数结果。最后,将结果打印输出。