熊猫在索引中旋转多列

时间:2019-03-16 08:31:53

标签: python-3.x pandas pivot

我有一个数据框:

In [1]: import pandas as pd 
   ...:  
   ...: df = pd.DataFrame([['dicts', 'oui_lookup', 'MergeTree', 'ipdr1']], colum
   ...: ns=['database', 'table', 'engine', 'server']) 
   ...: df                                                                      
Out[1]: 
  database       table     engine server
0    dicts  oui_lookup  MergeTree  ipdr1

我想旋转数据框以更改其格式。

In [3]: df.pivot(index='table', columns='server', values='engine')              
Out[3]: 
server          ipdr1
table                
oui_lookup  MergeTree

到目前为止,太好了。 现在我也想在索引数据库中使用,我尝试过:

In [4]: df.pivot(index=['database', 'table'], columns='server', values='engine')
   ...:                                                                         
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-c81911288ca4> in <module>
----> 1 df.pivot(index=['database', 'table'], columns='server', values='engine')

/usr/lib/python3.7/site-packages/pandas/core/frame.py in pivot(self, index, columns, values)
   5635     def pivot(self, index=None, columns=None, values=None):
   5636         from pandas.core.reshape.pivot import pivot
-> 5637         return pivot(self, index=index, columns=columns, values=values)
   5638 
   5639     _shared_docs['pivot_table'] = """

/usr/lib/python3.7/site-packages/pandas/core/reshape/pivot.py in pivot(data, index, columns, values)
    385         else:
    386             indexed = data._constructor_sliced(data[values].values,
--> 387                                                index=index)
    388     return indexed.unstack(columns)
    389 

/usr/lib/python3.7/site-packages/pandas/core/series.py in __init__(self, data, index, dtype, name, copy, fastpath)
    247                             'Length of passed values is {val}, '
    248                             'index implies {ind}'
--> 249                             .format(val=len(data), ind=len(index)))
    250                 except TypeError:
    251                     pass

ValueError: Length of passed values is 1, index implies 2

但是我得到了这个错误。 我需要的是这种形式的数据框:

Out[16]: 
                         ipdr1
database table                
dicts    oui_lookup  MergeTree

我做错了什么?

1 个答案:

答案 0 :(得分:1)

pivotDataFrame.set_indexSeries.unstack结合使用:

df1 = df.set_index(['database', 'table','server'])['engine'].unstack()
print (df1)
server                   ipdr1
database table                
dicts    oui_lookup  MergeTree
相关问题