相关疑难解决方法(0)

Pandas Pivot表行小计

我正在使用Pandas 0.10.1

考虑此数据帧:

Date       State   City    SalesToday  SalesMTD  SalesYTD
20130320     stA    ctA            20       400      1000
20130320     stA    ctB            30       500      1100
20130320     stB    ctC            10       500       900
20130320     stB    ctD            40       200      1300
20130320     stC    ctF            30       300       800
Run Code Online (Sandbox Code Playgroud)

我如何组合每个州的小计?

State   City  SalesToday  SalesMTD  SalesYTD
  stA    ALL          50       900      2100
  stA    ctA          20       400      1000
  stA    ctB          30       500      1100
Run Code Online (Sandbox Code Playgroud)

我尝试使用数据透视表,但我只能在列中使用小计

table = pivot_table(df, values=['SalesToday', 'SalesMTD','SalesYTD'],\
                     rows=['State','City'], aggfunc=np.sum, margins=True)
Run Code Online (Sandbox Code Playgroud)

我可以使用数据透视表在excel上实现这一点.

python pivot-table pandas

38
推荐指数
3
解决办法
4万
查看次数

Pandas,计算每个MultiIndex子级的总和

我想计算每个多指数子级的总和.然后,将其保存在数据框中.

我目前的数据框架如下:

                    values
    first second
    bar   one     0.106521
          two     1.964873
    baz   one     1.289683
          two    -0.696361
    foo   one    -0.309505
          two     2.890406
    qux   one    -0.758369
          two     1.302628
Run Code Online (Sandbox Code Playgroud)

并且所需的结果是:

                    values
    first second
    bar   one     0.106521
          two     1.964873
          total   2.071394
    baz   one     1.289683
          two    -0.696361
          total   0.593322
    foo   one    -0.309505
          two     2.890406
          total   2.580901
    qux   one    -0.758369
          two     1.302628
          total   0.544259
    total one     0.328331
          two     5.461546
          total   5.789877
Run Code Online (Sandbox Code Playgroud)

目前我发现下面的实现有效.但我想知道是否有更好的选择.我需要尽可能快的解决方案,因为在某些情况下,当我的数据帧变得庞大时,计算时间似乎需要很长时间.

In [1]: arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
   ...:           ['one', 'two', …
Run Code Online (Sandbox Code Playgroud)

python pandas

6
推荐指数
1
解决办法
2207
查看次数

python中的pandas数据操作

我有一个数据帧df的列IDN1,我想计算柱N2,用逻辑第一值应等于N1每个ID和下一个值是0.888/0.999等.对于下一个ID同样如此.我们可以这样做而不使用for循环pandas

ID  N1  N2
1111    0.999   0.999
1111    0.888   0.888888889
1111    0.777   0.875
1111    0.666   0.857142857
1111    0.555   0.833333333
1111    0.444   0.8
1111    0.333   0.75
2222    0.998   0.998
2222    0.887   0.888777555
2222    0.776   0.874859076
2222    0.665   0.856958763
2222    0.554   0.833082707
2222    0.443   0.799638989
2222    0.332   0.749435666
2222    0.221   0.665662651
Run Code Online (Sandbox Code Playgroud)

data-manipulation python-3.x pandas

3
推荐指数
1
解决办法
322
查看次数