我有一个数据框与数字列.对于每一列,我想计算分位数信息,并将每一行分配给其中之一.我试图使用
qcut() method返回一个分箱列表,而是最终单独计算箱子.我认为可能存在,但我找不到它将是一个方法,如df.to_quintile(数位数).这是我想到的,但我想知道是否有更多的succint /熊猫的方式这样做.
import pandas as pd
#create a dataframe
df = pd.DataFrame(randn(10, 4), columns=['A', 'B', 'C', 'D'])
def quintile(df, column):
"""
calculate quintiles and assign each sample/column to a quintile
"""
#calculate the quintiles using pandas .quantile() here
quintiles = [df[column].quantile(value) for value in [0.0,0.2,0.4,0.6,0.8]]
quintiles.reverse() #reversing makes the next loop simpler
#function to check membership in quintile to be used with pandas apply
def check_quintile(x, quintiles=quintiles):
for num,level in enumerate(quintiles):
#print number, level, level[1]
if x >= level:
print x, num
return num+1
df[column] = df[column].apply(check_quintile)
quintile(df,'A')
谢谢,
zach cp
编辑:看到帝斯曼答复后,功能可以写得更简单(下面).男人,那甜美
def quantile(column, quantile=5):
q = qcut(column, quantile)
return len(q.levels)- q.labels
df.apply(quantile)
#or
df['A'].apply(quantile)