2

I am using pandas and trying to replace a value with another value. What am I doing wrong?

Source

Drive-By
Referral
Website
Radio

My snippet:

import pandas as pd

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

Error:

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'
3
  • 6
    KeyError: 'Source' means that Source is not a valid header name within your data file. Are you sure you have the column names correct? Commented Jan 26, 2017 at 20:51
  • 2
    Could you post an output of print(second.columns.tolist()) after you read the CSV file (read_csv()...) - this will help toi understand what is wrong with your columns Commented Jan 26, 2017 at 20:55
  • Thanks @ Charles Morris. There is a semicolon in front of Source. Commented Jan 26, 2017 at 20:56

1 Answer 1

1

I believe that you can use the following as found in this answer:

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

This would normally replace the value in all columns, but if you don't have 'Drive-By' recurring in other columns, this should work ok.

However, your error message suggests that you have issues with 'Source' not being recognized as a key in the table.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.