1

I have the following dataframe created:

import pandas as pd
from numpy.random import randint
  
dict = {'Name':['Martha', 'Tim', 'Rob', 'Georgia'],
        'Maths':[87, 91, 97, 95],
        'Science':[83, 99, 84, 76]
       }
  
df = pd.DataFrame(dict)

Dataframe created Image

I want to add a location column and for a particular user Tim, I want to add location. Any short way to do it?

gremur
  • 1,645
  • 2
  • 7
  • 20
sudeep sharma
  • 11
  • 1
  • 2

1 Answers1

3

You can approach it this way -

  1. Get the desired user's index in the dataframe.
  2. Then for that index add location or any new column

To do (1):

userindex = df.index[df['Name'] == "Tim"]

To do (2):

df.loc[userindex, ["Location"]] = "Las Vegas"

As you can see, the loc function in pandas takes the row index and column index in order to assign a value.

Hope that answered your question. I see this is your first question in SOF, Happy questioning! :)