是否有更多的python方法可以从熊猫数据框架中四分之一



i在熊猫数据框架内具有1-843300范围内的列,我想将其分为4个等于pd.cut的相等部分。我想知道做这件事的最佳方式是什么?

DF称为" news_df"列标签为"共享",这就是我完成的方式:

max_shares = news_df.shares.max()
weight_bins = [1,max_shares*0.25,max_shares*0.5,max_shares*0.75,max_shares]

我正在使用Python3。

谢谢。

您可以使用pandas.qcut

示例:

df = pd.DataFrame({'Range':np.arange(1,14)})

    Range
0       1
1       2
2       3
3       4
4       5
5       6
6       7
7       8
8       9
9      10
10     11
11     12
df.assign(qbins = pd.qcut(df.Range, 4, labels=['1st', '2nd', '3rd', '4th']))

输出:

    Range qbins
0       1   1st
1       2   1st
2       3   1st
3       4   2nd
4       5   2nd
5       6   2nd
6       7   3rd
7       8   3rd
8       9   3rd
9      10   4th
10     11   4th
11     12   4th

您可以使用numpys linspace做到这一点。

import numpy as np
max_shares = 10 
weight_bins = np.linspace(0, max_shares, 5)
weight_bins[0] = 1
array([  1. ,   2.5,   5. ,   7.5,  10. ])

最新更新