我尝试使用数据透视表在 pivot_table 函数的“值”字段中有多个值,但它不起作用,所以我想看看我是否可以使用交叉表来做到这一点。 这是我的代码
table=pandas.pivot_table(xl2, values='Applications', rows='Sub-Product',cols='Application Date',aggfunc=numpy.sum)
当我导出到 csv 时我得到了这个。
Sub-Product 11/1/12 11/2/12 11/3/12
GP 190 207 65
GPF 1391 1430 1269
在 python 中,将其转换为数据透视表后,dtype 为 float64() 并使用
<class 'pandas.core.frame.DataFrame'>
我最终想要的是 csv 格式的输出:
Row Labels 11/1/2012 11/2/2012 11/3/2012
GP
Acquisitions 164 168 54
Applications 190 207 65
GPF
Acquisitions 1124 1142 992
Applications 1391 1430 1269
使用与此类似的代码(目前它不起作用:/):
table=pd.pivot_table(xl2, values=['Acquisitions','Applications'], rows=['Sub-Product'],cols=['Application Date'],aggfunc=np.sum)
但我只能得到这个:
Sub-Product ('Applications', Timestamp('2012-11-01 00:00:00', tz=None)) ('Applications', Timestamp('2012-11-02 00:00:00', tz=None)) ('Applications', Timestamp('2012-11-03 00:00:00', tz=None))
GP 190 207 65
GPF 1391 1430 1269
关于交叉表如何提供帮助的任何想法? :S
这是csv文件中的数据。我不确定为什么我不能将它们转换为正确的数据帧格式。
Application Date Sub-Product Applications Acquisitions
11/1/12 GP 1 1
11/1/12 GP 1 1
11/1/12 GP 1 1
11/1/12 GP 1 1
11/1/12 GPF 1 1
11/1/12 GPF 1 1
11/1/12 GPF 1 1
11/1/12 GPF 1 1
最佳答案
看起来你真的很接近你想去的地方。 table.stack(0)
会将列索引的第一级移动到行索引。
In [1]: import pandas as pd
In [2]: from StringIO import StringIO
In [3]: df = pd.read_csv(StringIO("""\
...: Application-Date Sub-Product Applications Acquisitions
...: 11/1/12 GP 1 1
...: 11/1/12 GPF 1 1
...: 11/2/12 GP 1 1
...: 11/2/12 GP 1 1
...: 11/2/12 GPF 1 1
...: 11/2/12 GPF 1 1
...: 11/3/12 GP 1 1
...: 11/3/12 GP 1 1
...: 11/3/12 GP 1 1
...: 11/3/12 GPF 1 1
...: 11/3/12 GPF 1 1
...: 11/3/12 GPF 1 1
...: """), sep='\s+', parse_dates=[0])
In [4]: table = df.pivot_table(values=['Acquisitions', 'Applications'],
...: rows='Sub-Product',
...: cols='Application-Date',
...: aggfunc=sum)
In [5]: table
Out[5]:
Applications Acquisitions
Application-Date 2012-11-01 2012-11-02 2012-11-03 2012-11-01 2012-11-02 2012-11-03
Sub-Product
GP 1 2 3 1 2 3
GPF 1 2 3 1 2 3
In [6]: table.stack(0)
Out[6]:
Application-Date 2012-11-01 2012-11-02 2012-11-03
Sub-Product
GP Applications 1 2 3
Acquisitions 1 2 3
GPF Applications 1 2 3
Acquisitions 1 2 3
关于python - 如何使用多维交叉表/数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18986822/