Binning一个python pandas数据帧:提取bin中心和另一列的和

2024-09-27 00:20:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一点麻烦,binbing一个熊猫数据帧,然后提取必要的绘图变量。在

我有一个pandas数据帧,如下所示:

            a    ad    td  price  result  profit_loss  
12935   10809 -1181  2363    262     1.0     616743.0  
13025  -18771   696  1390    350     1.0       1390.0  
13079  -20154   348   695    305     0.0        695.0  
13085    2370  3945  3150    264     0.0    -828450.0 

我想将数据帧的行放入“td”字段的等大小的存储箱中(例如td=0-100、100-200、200-300),并计算属于该td-bin的所有损益条目的总和

例如,对于0-2000年的td bin,盈亏为1390+695。在

然后,我想画出td bin中心与盈亏总额。在

我试过:

^{pr2}$

但我不知道如何提取td bin中心和创建的盈亏总额并绘制它们。在

谢谢!在


Tags: 数据绘图pandasbinresult中心pricead
2条回答

bin列添加到dataframe,然后groupby

一个bin应该是td - td%binsize+ binsize/2,如果你想要中心)。在

然后只要groupby越过bin就可以绘制出

>>> df['bin'] = df.td - df.td % 2000 + 1000
>>> s = df[['bin', 'profit_loss']].groupby('bin').sum()
>>> s
      profit_loss
bin              
1000       2085.0
3000    -211707.0
>>> s.plot(kind='bar')
<matplotlib.axes._subplots.AxesSubplot object at 0x7fce4fba3358>
>>> plt.show()

enter image description here

如果要在X轴上显示所有空箱子-可以这样做:

import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')

new = pd.DataFrame({'td':range(0, int(round(df.td.max() / 100) * 100) + 100, 100)})

(pd.merge(new, df.groupby(df.td//100*100)['profit_loss']
                 .sum().reset_index(),
          how='left')
   .fillna(0)
   .set_index('td')
   .plot.bar()
)
plt.axhline(0, color='k')

enter image description here

说明:

一个助手DF,包含所有垃圾箱

^{pr2}$

分组原始数据框

In [71]: df.groupby(df.td//100*100)['profit_loss'].sum().reset_index()
Out[71]:
     td  profit_loss
0   600        695.0
1  1300       1390.0
2  2300     616743.0
3  3100    -828450.0

合并/结果数据框

In [69]: (pd.merge(new, df.groupby(df.td//100*100)['profit_loss']
   ....:                  .sum().reset_index(),
   ....:           how='left')
   ....:    .fillna(0)
   ....: )
Out[69]:
      td  profit_loss
0      0          0.0
1    100          0.0
2    200          0.0
3    300          0.0
4    400          0.0
5    500          0.0
6    600        695.0
7    700          0.0
8    800          0.0
9    900          0.0
10  1000          0.0
11  1100          0.0
12  1200          0.0
13  1300       1390.0
14  1400          0.0
15  1500          0.0
16  1600          0.0
17  1700          0.0
18  1800          0.0
19  1900          0.0
20  2000          0.0
21  2100          0.0
22  2200          0.0
23  2300     616743.0
24  2400          0.0
25  2500          0.0
26  2600          0.0
27  2700          0.0
28  2800          0.0
29  2900          0.0
30  3000          0.0
31  3100    -828450.0
32  3200          0.0

相关问题 更多 >

    热门问题