[英]How to create a new column and insert value at a particular row in pandas dataframe?
I have the following dataframe created:我创建了以下 dataframe:
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.我想添加一个位置列,对于特定用户 Tim,我想添加位置。 Any short way to do it?
有什么捷径吗?
You can approach it this way -你可以这样处理它 -
To do (1):要做(1):
userindex = df.index[df['Name'] == "Tim"]
To do (2):要做(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.可以看到,pandas中的loc function为了赋值取了行索引和列索引。
Hope that answered your question.希望这回答了你的问题。 I see this is your first question in SOF, Happy questioning: :)
我看到这是您在 SOF 中的第一个问题,祝您提问愉快::)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.