3

将平面表数据转换为 3d 数组似乎有很多可能性,但我不知何故找不到一个可行的方法:假设我有一些数据,其中 columns=['name', 'type', 'date', '价值']。当我尝试通过

pivot(index='name', columns=['type', 'date'], values='value')

我明白了

ValueError: Buffer has wrong number of dimensions (expected 1, got 2)

我可能在阅读来自 dev pandas 的文档吗?似乎这是那里描述的用法。我正在运行 0.8 只熊猫。

我想,我想知道我是否有一个 MultiIndex ['x', 'y', 'z'] 系列,有没有一种熊猫方法可以将它放在面板中?我可以使用 groupby 并完成工作,但这几乎就像我在 numpy 中组装一个 nd 数组一样。似乎是一个相当通用的操作,所以我想它可能已经实现了。

4

2 回答 2

8

pivot仅支持使用单个列来生成列。您可能希望pivot_table使用多列生成数据透视表,例如

pandas.tools.pivot.pivot_table(your_dataframe, values='value', index='name', columns=['type', 'date'], aggfunc='sum')

API 参考文档中提到的分层列与pivot您有多个字段而不是多个类别的情况有关。

假设 'type' 和 'date' 是类别,它们的值应该用作列名,那么你应该使用pivot_table.

但是,如果您想为同一类别(例如“类型”)的不同值字段提供单独的列,那么您应该使用pivot而不指定值列和您的类别作为列参数。

例如,假设你有这个 DataFrame:

df = DataFrame({'name': ['A', 'B', 'A', 'B'], 'type': [1, 1, 2, 2], 'date': ['2012-01-01', '2012-01-01', '2012-02-01', '2012-02-01'],  'value': [1, 2, 3, 4]})

pt = df.pivot_table(values='value', index='name', columns=['type', 'date'])
p = df.pivot('name', 'type')

pt 将是:

type           1           2
date  2012-01-01  2012-02-01
name                        
A              1           3
B              2           4

和 p 将是:

          date              value   
type           1           2      1  2
name                                  
A     2012-01-01  2012-02-01      1  3
B     2012-01-01  2012-02-01      2  4

注意:对于 < 0.14.0 的 pandas 版本,indexcolumns关键字参数应分别替换为rowscols

于 2012-11-07T13:16:49.540 回答
4

原帖以问题结尾:

“我想知道我是否有一个 MultiIndex ['x', 'y', 'z'] 系列,有没有一种熊猫方法可以将它放在面板中?”

我自己正在寻找解决方案。

我最终得到以下结果:

In [1]: import pandas as pd

## generate xyz example:
In [3]: df = pd.DataFrame({col:pd.np.random.randint(0,10,10) 
                               for col in ['x','y','z','data']})

## set all x,y,z coordinates as indices
In [5]: df.set_index(['x','y','z'], inplace=True)

## set the z coordinate as headers of the columns 
# NB: this is will turn the data into "dense" with NaNs where there were no 'data'
In [7]: df = df['data'].unstack()

## now it is ready to be "pivot"ed into a panel
In [9]: data_panel = df.to_panel()

In [10]: df
Out[10]: 
     data                        
z       1   3   4   5   6   7   9
x y                              
1 5   NaN NaN NaN NaN NaN NaN   1
  6   NaN NaN NaN NaN NaN NaN   0
2 9   NaN NaN NaN NaN NaN   1 NaN
3 9     6 NaN NaN NaN NaN NaN NaN
5 9   NaN NaN NaN NaN NaN NaN   8
7 1   NaN NaN NaN NaN   8 NaN NaN
  3   NaN NaN NaN NaN NaN NaN   5
  7   NaN NaN NaN   1 NaN NaN NaN
  9   NaN   0 NaN NaN NaN NaN NaN
9 5   NaN NaN   1 NaN NaN NaN NaN

[10 rows x 7 columns]

In [11]: data_panel
Out[11]: 
<class 'pandas.core.panel.Panel'>
Dimensions: 7 (items) x 6 (major_axis) x 6 (minor_axis)
Items axis: 1 to 9
Major_axis axis: 1 to 9
Minor_axis axis: 1 to 9

列标题将是面板的项目,第一级索引是 MajorAxis(行),第二级是 MinorAxis(列)

于 2014-02-13T16:40:16.813 回答