设置
cats = ['0-30', '31-60', '61-90', '91-120', '121-150']
bins = [0, 30, 60, 90, 120, 150]
选项 1
使用pd.get_dummies 和pd.DataFrame.join
df[['item_code']].join(pd.get_dummies(pd.cut(df.price, bins, labels=cats)))
item_code 0-30 31-60 61-90 91-120 121-150
0 1 1 0 0 0 0
1 1 1 0 0 0 0
2 1 0 1 0 0 0
3 2 0 1 0 0 0
4 3 0 0 1 0 0
5 4 0 0 0 1 0
6 5 0 0 0 0 1
7 4 0 0 0 0 1
选项 2
使用 numpy 的 searchsorted 和一些字符串数组添加。
from numpy.core.defchararray import add
bins = np.arange(30, 121, 30)
b = bins.astype(str)
cats = add(add(np.append('0', b), '-'), np.append(b, '150'))
df[['item_code']].join(pd.get_dummies(cats[bins.searchsorted(df.price)]))
item_code 0-30 120-150 30-60 60-90 90-120
0 1 1 0 0 0 0
1 1 1 0 0 0 0
2 1 0 0 1 0 0
3 2 0 0 1 0 0
4 3 0 0 0 1 0
5 4 0 0 0 0 1
6 5 0 1 0 0 0
7 4 0 1 0 0 0
如果您要对价值 item_codes 的类似值求和。你可以用groupby代替join
from numpy.core.defchararray import add
bins = np.arange(30, 121, 30)
b = bins.astype(str)
cats = add(add(np.append('0', b), '-'), np.append(b, '150'))
pd.get_dummies(cats[bins.searchsorted(df.price)]).groupby(df.item_code).sum().reset_index()
item_code 0-30 120-150 30-60 60-90 90-120
0 1 2 0 1 0 0
1 2 0 0 1 0 0
2 3 0 0 0 1 0
3 4 0 1 0 0 1
4 5 0 1 0 0 0
选项 3
使用pd.factorize 和np.bincount 的一种非常快速的方法
from numpy.core.defchararray import add
bins = np.arange(30, 121, 30)
b = bins.astype(str)
cats = add(add(np.append('0', b), '-'), np.append(b, '150'))
j, c = pd.factorize(bins.searchsorted(df.price))
i, r = pd.factorize(df.item_code.values)
n, m = c.size, r.size
pd.DataFrame(
np.bincount(i * m + j, minlength=n * m).reshape(n, m),
r, cats).rename_axis('item_code').reset_index()
item_code 0-30 30-60 60-90 90-120 120-150
0 1 2 1 0 0 0
1 2 0 1 0 0 0
2 3 0 0 1 0 0
3 4 0 0 0 1 1
4 5 0 0 0 0 1