2017-06-19 38 views
0

我有哪些輸入數據:查找在大熊貓數據幀某一列的名稱和位置

  • 存儲在大熊貓數據幀具有定義的索引 和列名
  • 的長度相同的列表的三角矩陣列的數據幀數量
  • 一個函數,從列表中需要將項目作爲輸入

我想接下來要做什麼:

  • 應用功能基於在數據幀中的值列表
  • 情節的函數的結果基於所述數據幀

一個小例子的列從另一個列表中的每個項目:

scores = np.array([[1,2,1.5,0.75], 
       [0,1,0.75,1.25], 
       [0,0,1,2], 
       [0,0,0,1]]) 
names = ['Andy','Bob','Craig','Dan'] 

bets = [100,120,135,130] 

def getPrize(bet, x): # x defined somewhere elsewhere 
    prize = bet*x #do stuff here 
    return prize 

names1 = ['Andy1','Bob1','Craig1','Dan1'] 

Results = pd.DataFrame(data=scores,index=names1,columns=names1) 

現在,我定義在數據幀的值的條件,並基於該條件下,我想找到相關的列(整數值的位置,如果-conversely-我所用df.iloc找到它)。

我想什麼是這樣的:

for i, r in Results.iterrows(): 
    found = r[r>1] 
    col_index = r.columns.get_loc(found) 
    print col_index 

但在這裏我所面臨的問題AttributeError: 'Series' object has no attribute 'columns'。 但如果我寫這篇文章,而不是:

col_ix, col_name = found.iteritems() 

我得到ValueError: need more than 1 value to unpack - 所以我沒有使用正確iteritems?但是,如果我的值爲print,則會在拋出錯誤之前打印這些值。

最後,我想要在y軸上有一個「獎」,在x軸上有名字,繪製每個人所選獎項的值(以及條件)我試圖實現的另一件事是找到哪個項目的names列表是每個我的結果列名稱的子字符串)。

回答

1

的simpliest只是多:

print (results.mul(np.array(bets))) 
     Andy Bob Craig Dan 
Andy 100.0 240.0 202.50 97.5 
Bob  0.0 120.0 101.25 162.5 
Craig 0.0 0.0 135.00 260.0 
Dan  0.0 0.0 0.00 130.0 

但是,如果真正的功能是較爲複雜的DataFrame.apply

def getPrize(bet,score): 
    #working with Series score and list bets 
    print (bet) 
    print (score) 
    prize = bet*score 
    return prize 

df = results.apply(lambda x: getPrize(bets, x), axis=1) 
print (df) 

     Andy Bob Craig Dan 
Andy 100.0 240.0 202.50 97.5 
Bob  0.0 120.0 101.25 162.5 
Craig 0.0 0.0 135.00 260.0 
Dan  0.0 0.0 0.00 130.0 

plt.xticks(np.arange(len(df.columns)), df.columns) 
plt.plot(df.values) 

編輯:

如果所有列的需要位置是必要的list comprehension(或一些循環),因爲Index.get_loc只能與標量一起使用:

for i, r in Results.iterrows(): 
    found = r[r>1] 
    col_index = [r.index.get_loc(x) for x in found.index] 
    print (col_index) 

[1, 2] 
[3] 
[3] 
[] 
+0

我明白了!謝謝,很好的答案,但錯誤的問題。它不適用於我的真實數據,現在我明白了原因。我將編輯該問題。 – durbachit

+0

是的,我正在考慮你的問題,這取決於你的功能。你的功能是否真的很複雜,不適用於熊貓或numpy功能? – jezrael

+0

如果可能,最好的方法是添加所需的輸出,也許還需要更改輸入以便更好地理解。謝謝。 – jezrael