简体   繁体   中英

How to create a new column and insert value at a particular row in pandas dataframe?

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)

数据框创建图像

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

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: :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM