我有一个dataframe,我想按类别变量和一系列值进行分组你可以把它想象成一行行相似的值(集群?)例如:

df = pd.DataFrame({'symbol' : ['IP', 'IP', 'IP', 'IP', 'IP', 'IP', 'IP'],
                   'serie' : ['A', 'B', 'A', 'B', 'A', 'B', 'B'],
                   'strike' : [10, 10, 12, 13, 12, 13, 14],
                   'last' : [1, 2, 2.5, 3, 4.5, 5, 6],
                   'price' : [11, 11, 11, 11, 11, 11, 11],
                   'type' : ['call', 'put', 'put', 'put', 'call', 'put', 'call']})

如果我用
grouped = df.groupby(['symbol', 'serie', 'strike'])

我已经解决了部分问题,但我想将更接近的罢工值组合起来,如10和11、12和13等等最好在%范围内。

最佳答案

我猜OP希望按分类变量分组,然后是按间隔装箱的数字变量在这种情况下,您可以使用np.digitize()

smallest = np.min(df['strike'])
largest = np.max(df['strike'])
num_edges = 3
# np.digitize(input_array, bin_edges)
ind = np.digitize(df['strike'], np.linspace(smallest, largest, num_edges))

那么ind应该是
array([1, 1, 2, 2, 2, 2, 3], dtype=int64)

与宾宁相对应
 [10, 10, 12, 13, 12, 13, 14]

带箱子边缘
array([ 10.,  12.,  14.]) # == np.linspace(smallest, largest, num_edges)

最后,按所需的所有列分组,但使用此附加的bin列
df['binned_strike'] = ind
for grp in df.groupby(['symbol', 'serie', 'binned_strike']):
    print "group key"
    print grp[0]
    print "group content"
    print grp[1]
    print "============="

这个应该印出来
group key
('IP', 'A', 1)
group content
   last  price serie  strike symbol  type  binned_strike
0   1.0     11     A      10     IP  call              1
=============
group key
('IP', 'A', 2)
group content
   last  price serie  strike symbol  type  binned_strike
2   2.5     11     A      12     IP   put              2
4   4.5     11     A      12     IP  call              2
=============
group key
('IP', 'B', 1)
group content
   last  price serie  strike symbol type  binned_strike
1   2.0     11     B      10     IP  put              1
=============
group key
('IP', 'B', 2)
group content
   last  price serie  strike symbol type  binned_strike
3   3.0     11     B      13     IP  put              2
5   5.0     11     B      13     IP  put              2
=============
group key
('IP', 'B', 3)
group content
   last  price serie  strike symbol  type  binned_strike
6   6.0     11     B      14     IP  call              3
=============

关于python - 如何按 Pandas 的一系列值(value)分组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36118122/

10-16 00:58
查看更多