pandas concat是不可能得到错误的原因

时间:2014-02-05 16:43:02

标签: python pandas

我喜欢在我的枢轴顶部添加一个总行,但是当我试图连接时,我得到了一个错误。

>>> table
          Weight                        
Vcountry       1   2   3   4   5   6   7
V20001                                  
1             86 NaN NaN NaN NaN NaN  92
2             41 NaN  71  40  50  51  49
3            NaN  61  60  61  60  25  62
4             51 NaN NaN NaN NaN NaN NaN
5             26  26  20  41  25  23 NaN

[5 rows x 7 columns]

这是数据透视表

>>> totals_frame
Vcountry      1   2    3    4    5   6    7
totalCount  204  87  151  142  135  99  203

我想加入的总数

[1 rows x 7 columns]
>>> pc = [totals_frame, table]
>>> concat(pc)

这里输出:

reindex_items
    copy_if_needed=True)
  File "C:\Python27\lib\site-packages\pandas\core\index.py", line 2887, in reindex
    target = MultiIndex.from_tuples(target)
  File "C:\Python27\lib\site-packages\pandas\core\index.py", line 2486, in from_tuples
    arrays = list(lib.tuples_to_object_array(tuples).T)
  File "inference.pyx", line 915, in pandas.lib.tuples_to_object_array (pandas\lib.c:43656)
TypeError: object of type 'long' has no len()

1 个答案:

答案 0 :(得分:0)

这是一种可行的方法:而不是使用pd.concat使用pd.DataFrame.append。有一些摆弄指数要做,但我认为它仍然很整洁:

# Just setting up the dataframe:
df = pd.DataFrame({'country':['A','A','A','B','B','B'],
                   'weight':[1,2,3,1,2,3],
                   'value':[10,20,30,15,25,35]})
df = df.set_index(['country','weight']).unstack('weight')

# A bit of messing about to get the index right:
index = df.index.values.tolist()
index.append('Totals')

# Here's where the magic happens:
df = df.append(df.sum(), ignore_index=True)
df.index = index

给出:

        value        
weight      1   2   3
A          10  20  30
B          15  25  35
Totals     25  45  65