简体   繁体   English

如何在 pandas dataframe 中的特定行创建一个新列并插入值?

[英]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 -你可以这样处理它 -

  1. Get the desired user's index in the dataframe.在 dataframe 中获取所需用户的索引。
  2. Then for that index add location or any new column然后为该索引添加位置或任何新列

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.

相关问题 如何根据 Pandas dataframe 中上一行的行值创建新列? - How to create a new column based on row value in previous row in Pandas dataframe? 在 pandas 中,如何将新行插入 dataframe 一次一列值 - In pandas, how do I insert a new row into a dataframe one column value at a time 在 Pandas DataFrame 中创建一个具有特定值的列 - Create a column with particular value in pandas DataFrame 如何在 pandas dataframe 的特定行和列中插入输入值 - How to insert a value from an input in a specific row and column in a pandas dataframe Pandas:如何根据每行包含 json 的列值创建新的 dataframe? - Pandas: how to create a new dataframe depending on a column value containing json for each row? 如何在数据框中拆分一列并将每个值存储为新行(以熊猫为单位)? - How to split a column in a dataframe and store each value as a new row (in pandas)? 如何使用pandas数据帧中第一行和相应行之间的列的平均值填充特定值 - How to fill a particular value with mean value of the column between first row and the corresponding row in pandas dataframe 根据行中的值是否再次出现在数据框中,在pandas数据框中创建新列 - Create new column in pandas dataframe based on whether a value in the row reappears in dataframe 当同一行中的另一列为NaN时,如何从熊猫数据框中选择特定的列值? - How to select a particular column value from a pandas dataframe when another column in the same row is NaN? 根据熊猫列中的值从DataFrame中选择特定的行 - Select particular row from a DataFrame based on value in a column in pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM