2016-03-03 37 views
1

假設我有一個數據幀,如:追加一個系列作爲行數據幀熊貓(Python的3.4)

df2 = pd.DataFrame({ 'A' : 1., 
        'B' : pd.Timestamp('20130102'), 
        'C' : pd.Series(1,index=list(range(4)),dtype='float32'), 
        'D' : np.array([3] * 4,dtype='int32'), 
        'E' : pd.Categorical(["test","train","test","train"]), }) 

這看起來像

A B   C D E   
0 1 2013-01-02 1 3 test  
1 1 2013-01-02 1 3 train 
2 1 2013-01-02 1 3 test  
3 1 2013-01-02 1 3 train 

我想追加一個「彙總」行對於數字列,並將在「彙總」在列E.

所以我有什麼是:

totals=pd.Series('Total', index=['E']) 
totals = df2.sum(numeric_only=True).append(totals) 

這將產生

totals 
A  4 
C  4 
D  12 
E Total 
dtype: object 

所以,如果我嘗試

df2.append(totals, ignore_index=True) 

我得到

A B      C D E 
0 1 2013-01-02 00:00:00 1 3 test 
1 1 2013-01-02 00:00:00 1 3 train 
2 1 2013-01-02 00:00:00 1 3 test  
3 1 2013-01-02 00:00:00 1 3 train 
4 4 NaN     4 12 NaN 

我在這裏的問題是,爲什麼沒有列 'E' 有一個 「總計」,爲什麼它是NaN嗎?

回答

0

不知道爲什麼,但略有改變。

total = df2.sum() 
total = total.append(pd.Series('Total', index=['E'])) 
df2.append(total, True) 

希望有幫助!

+0

它不適合我。 – jezrael

0

你必須設置categories與類別Totalcategories=["test","train","Total"]

我想你會得到NaN,因爲這個類別不存在。

import pandas as pd 
import numpy as np 


df2 = pd.DataFrame({ 'A' : 1., 
        'B' : pd.Timestamp('20130102'), 
        'C' : pd.Series(1,index=list(range(4)),dtype='float32'), 
        'D' : np.array([3] * 4,dtype='int32'), 
        'E' : pd.Categorical(["test","train","test","train"], 
              categories=["test","train","Total"])}) 


totals=pd.Series('Total', index=['E']) 
totals = df2.sum(numeric_only=True).append(totals) 
print df2.append(totals, True) 
    A   B C D  E 
0 1 2013-01-02 1 3 test 
1 1 2013-01-02 1 3 train 
2 1 2013-01-02 1 3 test 
3 1 2013-01-02 1 3 train 
4 4  NaT 4 12 Total 
0

首先,除非它是現有類別(即「測試」或「火車」),否則您將在列E中獲得NaN。因此,首先我們必須將新值Total添加到類別中,並將結果重新分配給列。

完成此操作後,您的原始方法將起作用。然而,我相信這是更直接的方法:

df2['E'] = df2.E.cat.add_categories('Total') 
df2.ix[len(df2)] = df2.sum() 
df2.iat[-1, -1] = 'Total' 

>>> df2 
    A   B C D  E 
0 1 2013-01-02 1 3 test 
1 1 2013-01-02 1 3 train 
2 1 2013-01-02 1 3 test 
3 1 2013-01-02 1 3 train 
4 4  NaT 4 12 Total