2017-01-26 89 views
2

我正在使用熊貓並嘗試用另一個值替換值。我究竟做錯了什麼?使用熊貓更改列值

Source 

Drive-By 
Referral 
Website 
Radio 

我的片段:

import pandas as pd 

second = pd.read_csv('T:/pythonfiles/result2.csv') 
second['Source'] = second['Source'].replace('Drive-By', 'Drive-by') 

錯誤:

File "pandas/src/hashtable_class_helper.pxi", line 732, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13161) 
File "pandas/src/hashtable_class_helper.pxi", line 740, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13115) 
KeyError: 'Source' 
+6

'KeyError:'Source''表示Source不是數據文件中的有效標頭名稱。你確定你的列名是否正確? – Chuck

+2

您可以在讀取CSV文件('read_csv()'...)後輸出'print(second.columns.tolist())' - 這將有助於理解您的列有什麼問題 – MaxU

+0

Thanks @查爾斯莫里斯。 Source前面有一個分號。 –

回答

1

我相信你可以使用以下作爲this answer發現:

second.replace({'Drive-By': 'Drive-by'}, regex=True) 

這通常取代所有的價值列,但如果您沒有在其他列中重複出現的「Drive-By」,則應該可以正常工作。

但是,您的錯誤消息表明您在「表」中沒有將「源」識別爲鍵的問題。