指定分界点分箱 【cut】
import pandas as pd
year = [1992, 1983, 1922, 1932, 1973] # 待分箱数据
bin = [1900,1950,2000] # 指定箱子的分界点
i = pd.cut(year,bin)
print(i)
[(1950, 2000], (1950, 2000], (1900, 1950], (1900, 1950], (1950, 2000]]
对不同箱子中的数进行计数
print(pd.value_counts(i))
(1950, 2000] 3
(1900, 1950] 2
labels参数为False时,返回结果中用不同的整数作为箱子的指示符
i = pd.cut(year,bin,labels = False)
print(i)
[1 1 0 0 1] #1是(1950, 2000] 0是(1900, 1950]
对不同箱子中的数进行计数
i = pd.cut(year,bin,labels = False)
print(pd.value_counts(i))
1 3
0 2
可以将想要指定给不同箱子的标签传递给labels参数
import pandas as pd
year = [1992, 1983, 1922, 1932, 1973]
bin = [1900,1950,2000]
name = ['50年代前','50年代后']
i = pd.cut(year,bin,labels = name)
print(pd.value_counts(i))
50年代后 3
50年代前 2
等频分箱 【qcut】
import pandas as pd
year = [1992, 1983, 1922, 1932, 1973, 1999, 1993, 1995] # 待分箱数据
i = pd.qcut(year,q=4) # 参数q指定所分箱子的数量
print(i)
print(pd.value_counts(i))
[(1987.5, 1993.5], (1962.75, 1987.5], (1921.999, 1962.75], (1921.999, 1962.75], (1962.75, 1987.5], (1993.5, 1999.0], (1987.5, 1993.5], (1993.5, 1999.5]
(1921.999, 1962.75] 2
(1962.75, 1987.5] 2
(1987.5, 1993.5] 2
(1993.5, 1999.0] 2