如何从交叉表订购箱子

2024-05-16 02:10:56 发布

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

我试图从这样的数据帧创建一个频率表:

scm=pd.read_csv('carac_scm.csv')
scm=scm[0:30][['Hora_inicio','Forma','AreaMax']]
scm
            Hora_inicio  Forma    AreaMax
0   2004-04-09 22:45:00  MBCCM       58
1   2004-04-12 22:45:00  MBSCL       86
2   2004-04-24 03:45:00    SCL      141
3   2004-05-02 06:45:00    SCL      108
4   2004-05-30 04:45:00  MBCCM       64
5   2004-05-31 03:15:00  MBCCM       77
6   2004-06-08 00:15:00  MBSCL       51
7   2004-06-12 22:15:00    CCM       73
8   2004-06-13 02:45:00  MBCCM       87
9   2004-06-13 23:45:00  MBSCL       54
10  2004-06-14 03:15:00  MBSCL       70
11  2004-06-17 08:15:00  MBCCM       47
12  2004-06-17 11:45:00  MBCCM       76
13  2004-06-22 00:15:00    SCL       76
14  2004-06-22 07:45:00  MBCCM      115
15  2004-06-22 22:45:00    CCM       98
16  2004-07-01 05:15:00  MBCCM       57
17  2004-07-02 00:15:00  MBSCL       61
18  2004-07-04 11:45:00  MBCCM       50
19  2004-07-06 03:45:00    SCL       77
20  2004-07-07 04:15:00    CCM       51  
21  2004-07-08 02:45:00  MBCCM       49
22  2004-07-08 11:45:00  MBCCM       40
23  2004-07-08 02:15:00  MBCCM       74
24  2004-07-09 04:45:00    CCM       39
25  2004-07-11 18:15:00  MBSCL       59
26  2004-07-11 23:15:00  MBSCL       85   
27  2004-07-15 10:45:00    CCM       51
28  2004-07-16 12:15:00  MBCCM       53
29  2004-07-17 02:15:00  MBCCM       80

现在我点了scm.AreaMax公司,以便得到最好的垃圾箱。为此,使用“cut module”并添加一个名为bins的新列,其中包含生成的间隔。下面的代码是上面描述的示例:

^{pr2}$

现在创建一个频率表来绘制堆积条形图,然后进行下一步:

df=pd.crosstab(rows=[scm['bins']],cols=[scm['Forma']],margins=False)
df
Forma       CCM  MBCCM  MBSCL  SCL
bins                              
(110, 130]    0      1      0    0
(130, 150]    0      0      0    1
(30, 50]      1      4      0    0
(50, 70]      2      4      5    0
(70, 90]      1      5      2    2
(90, 110]     1      0      0    1

df.plot(kind='bar', stacked=True)

{1美元^

怎么订箱子才能得到这样的桌子?在

Forma       CCM  MBCCM  MBSCL  SCL
bins                              
(30, 50]      1      4      0    0
(50, 70]      2      4      5    0
(70, 90]      1      5      2    2
(90, 110]     1      0      0    1
(110, 130]    0      1      0    0
(130, 150]    0      0      0    1

我试图用下面的代码行来获得这个结果,但是没有得到预期的结果

df.sort()  #Get the same table 
df.sort_index()   # Get the same table
df.sort_index(ascending=False)

  Forma       CCM  MBCCM  MBSCL  SCL
  bins                              
(90, 110]     1      0      0    1
(70, 90]      1      5      2    2
(50, 70]      2      4      5    0
(30, 50]      1      4      0    0
(130, 150]    0      0      0    1
(110, 130]    0      1      0    0

谁能给我提个主意吗?在


Tags: csvdfscmsortccm频率pdforma
1条回答
网友
1楼 · 发布于 2024-05-16 02:10:56

而“索引”是unicode,因为这是'110/gt;' 您可以创建一个数字列进行排序,然后删除。在

df['sort_col'] = [float(s.split(',')[0][1:]) for s in df.index]
df.sort(columns= 'sort_col',inplace=True)
del df['sort_col'] #You don't want to plot this col
df.plot(kind='bar', stacked=True)

相关问题 更多 >