python pandas dataframe仅为阈值

时间:2016-05-30 13:29:27

标签: python pandas dataframe count bin

在python pandas数据框“df”中,我有以下三列:

song_id | user_id | play_count

play_count =用户收听歌曲的次数

我正在尝试根据播放次数向此表添加列“评级”。 例如,如果play_count = 2,则评级将为“1”。

首先,我需要为1-10评级系统建立评级阈值。

df.play_count.describe()
count    393727.000000
mean          2.567627
std           4.822111
min           1.000000
25%           1.000000
50%           1.000000
75%           2.000000
max         771.000000
Name: play_count, dtype: float64

大多数play_counts都在1到200之间:

pd.value_counts(pd.cut(df.play_count, bins = 10))
(0.23, 78]    393576
(78, 155]        129
(155, 232]        13
(232, 309]         6
(309, 386]         2
(694, 771]         1
(617, 694]         0
(540, 617]         0
(463, 540]         0
(386, 463]         0
dtype: int64

我想创建10个桶,最后一个桶是如果play_count高于200,则该歌曲的评级为“10”。所以我需要建立其他9个桶的阈值。

不幸的是,这不起作用:

pd.value_counts(pd.cut(df[['play_count'] < 200]], bins = 9))
f = df[df['play_count'] < 200].hist()

1 个答案:

答案 0 :(得分:1)

# get threshholds for first 9 bins
_, bins = pd.cut(df[df.play_count < 200].play_count, bins=9,retbins=True)

# append threshhold representing class with play_counts > 200
new_bins = pd.np.append(bins,float(max(df.play_count)))

# our categorized data
out = pd.cut(df.play_count,bins=new_bins)

# a histogram of the data with the updated bins
df.play_count.hist(bins=new_bins)