2015-05-14 38 views
0

注 - 我問這個問題,假設我的問題是與數據幀的構造,但實際上我的問題是與iterrows()從排列表創建數據幀,並遍歷它

我想創建一個大熊貓數據幀從列表中取出一行,其中每一行都是值列表。我曾嘗試以下:

multigram_counts = [ 
    ["happy birthday", 23], 
    ["used below", 10], 
    ["frame for", 2] 
] 
df = pd.DataFrame(multigram_counts, columns = ["phrase", "count"]) 
df_iter = df.iterrows() 
frow = df_iter.next() 
self.assertEqual(frow['phrase'], "happy birthday") 

,但我得到了以下錯誤:

TypeError: tuple indices must be integers, not str 

我該如何解決這個問題,使我在「assertEqual便」功能,這兩個參數確實是平等的嗎?也就是說,我希望frow ['phrase']等於「生日快樂」。

+1

你的代碼沒有什麼意義,首先發布的內容你想要的輸出是,其次你創建的df沒有值作爲列表,但單個str值,第三,什麼是「專長」列?它在你的代碼中無處? – EdChum

+0

我期望的值在assertEqual函數中,我假定熟悉單元測試。用短語vs專長的錯字...感謝您的支持! – Selah

回答

2

df_iter包含(索引行)作爲一個元組,只得到該行,試試這個:

f_index, frow = df_iter.next() 
1

你的frow變量是一個元組,你稱它爲字典,如果我是你,我會調試它以知道frow的值是多少。

1

以下爲我的作品,如果你只是想在第一行,然後使用iloc

In [99]: 

multigram_counts = [ 
    ["happy birthday", 23], 
    ["used below", 10], 
    ["frame for", 2] 
] 
df = pd.DataFrame(multigram_counts, columns = ["phrase", "count"]) 
​ 
df.iloc[0]['phrase'] == 'happy birthday' 
Out[99]: 
True 

DF看起來是這樣的:

In [100]: 

df 
Out[100]: 
      phrase count 
0 happy birthday  23 
1  used below  10 
2  frame for  2