2016-09-17 70 views
0

我申請這個功能在數據幀df1應用numpy的功能,如下列:在整個數據幀

      AA   AB    AC   AD 
2005-01-02 23:55:00  "EQUITY" "EQUITY"  "EQUITY"  "EQUITY" 
2005-01-03 00:00:00  32.32  19.5299  32.32  31.0455 
2005-01-04 00:00:00  31.9075  19.4487  31.9075  30.3755 
2005-01-05 00:00:00  31.6151  19.5799  31.6151  29.971 
2005-01-06 00:00:00  31.1426  19.7174  31.1426  29.9647 

def func(x): 
    for index, price in x.iteritems(): 
     x[index] = price/np.sum(x,axis=1) 
    return x[index] 

df3=func(df1.ix[1:]) 

不過,我只得到單列返回,而不是3

2005-01-03 0.955843 
    2005-01-04 0.955233 
    2005-01-05 0.955098 
    2005-01-06 0.955773 
    2005-01-07 0.955877 
    2005-01-10  0.95606 
    2005-01-11  0.95578 
    2005-01-12 0.955621 

我猜測我錯過了公式中的一些內容,使其適用於整個數據框。另外我怎麼能返回其行中的字符串的第一個索引?

回答

2

你需要做的是通過以下方式:

def func(row): 
    return row/np.sum(row) 
df2 = pd.concat([df[:1], df[1:].apply(func, axis=1)], axis=0) 

它有2個步驟:

  1. df[:1]提取第一行,其中包含字符串,而df[1:]代表數據幀的其餘部分。稍後將它們連接起來,這將回答問題的第二部分。
  2. 對於在行上操作,您應該使用apply()方法。
+0

謝謝!!完美 – uniXVanXcel

+0

如果我想用每個單元格中的值除總和(行),我會簡單地做np.sum(row)/ row right? thnks – uniXVanXcel

+1

是的。你就是這麼做的。 – Ujjwal