2017-11-25 245 views
1

Image of how my dataframe looks at the minute如何根據Python數據框中存在的值將值添加到新列中?

我想把一個新的列放到我的數據框中,名爲「議會」,這將基於鎮字段。舉例來說,如果Town == Belfast,我想新的專欄委員會保持價值貝爾法斯特。但要注意的是,這些議會的一些價值觀與城鎮並不相同。另一個例子可能是,鎮可能是Clogher,我想把理事會價值弗馬納。我對Python非常陌生,非常感謝任何幫助。如果您需要更多我已經遺漏的信息,請詢問。 (到目前爲止,我只對貝爾法斯特市議會地區嘗試過)

我想要做的是循環遍歷數據框中的每一行並檢查「城鎮」列。如果城鎮欄目等於「貝爾法斯特」那麼我想將價值「貝爾法斯特」輸入一個名爲「議會」的新欄目。

count = 0 
for index, row in PsniYear1617Cleaned.iterrows(): 
    grabtown = PsniYear1617Cleaned["Town"] 
    for value in grabtown: 
     if value["Town"][0] == "Belfast": 
      PsniYear1617Cleaned.set_value(index, 'Council', value["Belfast"]) 
      count = count + 1 

TypeError
Traceback (most recent call last) <ipython-input-122-31f11c973fc5> in <module>() 3 grabtown = PsniYear1617Cleaned["Town"] 4 for value in grabtown: ----> 5 if value["Town"][0] == "Belfast": 6 PsniYear1617Cleaned.set_value(index, 'Council', value["Belfast"]) 7 count = count + 1

類型錯誤:字符串索引必須是整數,而不是str`

+0

你的意思''中pandas' dataframe'? – furas

+0

我很抱歉,我正在使用熊貓 – Sta1995

+0

所有的代碼都沒有任何意義 - 'pandas'可以在沒有'for'循環的情況下使用數據 – furas

回答

0

我想你需要通過所有可能town s的不同council創建dictionary對馬平,然後用replace

d = {'Enniskillen':'Fermanagh', 
    'Clogher':'Fermanagh', 
     'town1':'council1', 
     ...} 

PsniYear1617Cleaned['council'] = PsniYear1617Cleaned['Town'].replace(d) 
+0

謝謝,這正是我正在尋找的東西,對我來說是最簡單的解決方案。完美的答案,非常感謝。 – Sta1995

0
PsniYear1617Cleaned[:,'council'] = PsniYear1617Cleaned['Town'].apply(lambda x: TOWN_MAP[x]) 

在這種情況下,你有一個小鎮地圖存儲所有針對給定鎮和相應的議會拉姆達將完成其餘的工作。

相關問題