是否有一种更为python的方法将数据帧中的列四分之一?
我在pandas数据框中有一列,范围为1-843300,为了pd.cut的目的,我想将其分成4个相等的部分。我想知道做这件事最像蟒蛇的方式是什么 df被称为“news_df”,列标签是“shares”,我是这样做的:是否有一种更为python的方法将数据帧中的列四分之一?,python,pandas,Python,Pandas,我在pandas数据框中有一列,范围为1-843300,为了pd.cut的目的,我想将其分成4个相等的部分。我想知道做这件事最像蟒蛇的方式是什么 df被称为“news_df”,列标签是“shares”,我是这样做的: max_shares = news_df.shares.max() weight_bins = [1,max_shares*0.25,max_shares*0.5,max_shares*0.75,max_shares] 我正在使用Python 3 谢谢。您可以使用numpys l
max_shares = news_df.shares.max()
weight_bins = [1,max_shares*0.25,max_shares*0.5,max_shares*0.75,max_shares]
我正在使用Python 3
谢谢。您可以使用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. ])
您可以使用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. ])
你可以用
例如:
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
你可以用
例如:
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
我想你可以用pd.qcut做这一步,我想你可以用pd.qcut做这一步。