2015-12-02 124 views
-1

我們如何添加額外的一行str到熊貓數據框?熊貓數據框 - 添加行評論

最小工作例如:

In [65]: header_list = ['MU', 'Ars', 'THo'] 
    ...: team =['MU', 'Ars', 'THot'] 
    ...: w = [1,4,5] 
    ...: data = [] 
    ...: for n, line in enumerate(w, 1): 
    ...:  temp = [] 
    ...:  temp.append(w[n-1]) 
    ...:  temp.append(w[n-1]+1) 
    ...:  temp.append(w[n-1]-1) 
    ...:  data.append(temp) 
    ...: pd = pandas.DataFrame(data, team, header_list) 

數據幀將被保存到一個CSV文件。

pd.to_csv(os.path.join(new_directory, base_filename), index=True, sep=',', doublequote=True, escapechar=None, 
      decimal='.') 
Out[65]: 
     MU Ars THo 
MU  1 2 0 
Ars 4 5 3 
THot 5 6 4 

我如何追加字符串的一個額外行的數據幀,例如:平均值是:(平均第三列的數值)

+0

您可以創建一個額外的行,就像創建原始三行一樣。 – BrenBarn

+0

我試過了,得到了錯誤信息'Expected list,got str' –

+0

你試過了什麼? – Alexander

回答

1

大熊貓版本0.13,您可以使用loc

d.loc['Avg'] = d.mean() 
1

你必須使用loc作爲雷達建議。這裏是完整的示例代碼,只計算第三列的平均值

test_df =pd.DataFrame(np.arange(9).reshape(3,3)) 
mean= test_df[2].mean()#2 represents 3rd column name 
avg_row = ['The average is' , '' ,mean] 
test_df.loc[len(test_df)] =avg_row 
test_df 

Out[113]: 
       0 1 2 
0    0 1 2 
1    3 4 5 
2    6 7 8 
3 The average is  5