我有一个数据框,想要按一系列值过滤或bin,然后获取每个bin中的值计数。
目前,我正在这样做:
x = 5
y = 17
z = 33
filter_values = [x, y, z]
filtered_a = df[df.filtercol <= x]
a_count = filtered_a.filtercol.count()
filtered_b = df[df.filtercol > x]
filtered_b = filtered_b[filtered_b <= y]
b_count = filtered_b.filtercol.count()
filtered_c = df[df.filtercol > y]
c_count = filtered_c.filtercol.count()
但有没有更简洁的方法来完成同样的事情?
答案 0 :(得分:35)
也许您正在寻找pandas.cut:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(50), columns=['filtercol'])
filter_values = [0, 5, 17, 33]
out = pd.cut(df.filtercol, bins=filter_values)
counts = pd.value_counts(out)
# counts is a Series
print(counts)
产量
(17, 33] 16
(5, 17] 12
(0, 5] 5
要重新排序结果以便按顺序显示bin范围,可以使用
counts.sort_index()
产生
(0, 5] 5
(5, 17] 12
(17, 33] 16