Home > Back-end >  Python: How to replace a column value with a new value without knowing its existing value?
Python: How to replace a column value with a new value without knowing its existing value?

Time:12-31

I have a csv file with the below data.

enter image description here

Now, I want to replace any column value for all the rows with my required data without knowing the existing data present in the column.

Let's say, I want to replace all the values for "ofc Code" with "989".

I have tried below code:

import pandas as pd
import sys
csvFilePath=sys.argv[1]
columnName=sys.argv[2]
existingValue=int(sys.argv[3])
valueToBeUpdated=sys.argv[3]
df = pd.read_csv(csvFilePath)
df[columnName] = df[columnName].astype(object).replace({existingValue: valueToBeUpdated})
df.to_csv(csvFilePath, index=False)

Here the problem is I am accepting existing value of the column to replace it with new value. But the values in the column are dynamic. So I don't want to get that as input but replace all the values of the column with new value.

Pls help.

CodePudding user response:

Create dictionary for columns names with replacement values and pass to DataFrame.assign:

d = {columnName : valueToBeUpdated}

df = df.assign(**d)

If only one column name:

df[columnName] = valueToBeUpdated
  • Related