-1

I have two columns in a CSV File, let's reference them as 'Current' and 'New'.

I would like to replace all strings in df['Names'] that contain a value in 'Current' with the corresponding value in 'New'.

My current dataframe:

Names
Joseph
Robert

My current code:

df['Names'] = df['Names'].replace('Joseph', 'Joe') 
df['Names'] = df['Names'].replace('Robert', 'Rob') 

My expected result:

Names
Joe
Rob

However, the list of replacements is huge, so I need a different more efficient method to replace the values. I would need to use a CSV file rather than a dictionary to hold the values to replace. The CSV file 'replace.csv' is set out as follows:

Current New
Joseph Joe
Robert Rob
Fonti
  • 133
  • 1
  • 9
  • can you share a small example of the dataframe and your expected result? – Sreeram TP Feb 15 '22 at 04:46
  • It's not clear why you cannot replace the entire column at once just by assignment. df['Names'] = New_values. – Mehdi Shishehbor Feb 15 '22 at 05:12
  • Thank you for your reply, however not every value will need to be replaced. Some names, such as John, won't have abbreviations and the CSV file only has a list of the names with abbreviations that need to be changed. – Fonti Feb 15 '22 at 05:14

1 Answers1

0

Please check this question. Replacing few values in a pandas dataframe column with another value Check the answer from Preston. It should help you.

Basically the idea here is that, you can construct a dictionary with column name as keys and value as another dictionary with required strings to be updated. See example below. [Copied from same answer]

You could also pass a dict to the pandas.replace method

df.replace({
    'column_name': {
        'value_to_replace': 'replace_value_with_this',
        'foo': 'bar',
        'spam': 'eggs'
    },
    'other_column_name': {
        'other_value_to_replace': 'other_replace_value_with_this'
    },
    ...
})
Manjunath K Mayya
  • 1,078
  • 1
  • 11
  • 20
  • Thank you for your answer, is there anyway to pass my CSV file into that dictionary format? – Fonti Feb 15 '22 at 05:14
  • You could try to create a dictionary from the csv file. Refer this post for creating dictionary from csv file https://stackoverflow.com/questions/6740918/creating-a-dictionary-from-a-csv-file – Manjunath K Mayya Feb 15 '22 at 05:22