0

I'm trying to fill a column with values based on an if condition.

I have something like this at the moment..

review action
poor null
ok null
excellent null
poor null

and I need for example:

  • review = poor, action = terminate
  • review = ok, action = n/a
  • review = excellent, action = prize

below is the code I wrote.

file = performance_review.csv
headers = ['review', 'action']

with open(file, 'a+', newline="") as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=headers)
    writer.writeheader()
    writer.writerows(performance_review)
    for row in csvfile:
        if row["review"] == "poor":
            row["action"] = "terminate"
        elif row["review"] == "excellent":
            row["action"] = "prize"
        else:
            row["action"] = "NA"
        writer.writerows(row)
        file.close()
        
with open(file, 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

when I printed out the csv, action column remained blank and nothing was filled in. can someone shed a light please?

below is what i expected and wanted.

review action
poor terminate
ok n/a
excellent prize
poor terminate

much appreciated!

ScottC
  • 3,941
  • 1
  • 6
  • 20
xu4u06
  • 1
  • 1
  • 1
    as you tagged pandas, use `df['review'].map({'poor': 'terminate', 'excellent': 'prize'})` – mozway Dec 09 '22 at 09:51

0 Answers0