python - 如何为现有的 pandas 数据框添加新的索引行?

标签 python pandas dataframe

我有一个 Python Pandas 2D 数据框,其中 ITEM 列是索引。

ITEM   | A | B
ITEM-1 | 1 | 3
ITEM-2 | 1 | 2
ITEM-3 | 2 | 2

我有一个为脚本读取的新 JSON 创建新列的过程。如果此 JSON 响应中包含的项目已存在于数据框中,则该值将分配给现有的 ITEM 和新列。假设我想将值 3 添加到 ITEM-1 到新列 C。

ITEM   | A | B | C
ITEM-1 | 1 | 3 | 1
ITEM-2 | 1 | 2 |
ITEM-3 | 2 | 2 |

但是如果数据框中不存在该项目,我需要为数据框创建一个新行并为这个新行 X 列分配值。假设我想将值 2 添加到 ITEM-4(新项目)到新列 C(这是我的挑战)。

ITEM   | A | B | C
ITEM-1 | 1 | 3 | 1
ITEM-2 | 1 | 2 |
ITEM-3 | 2 | 2 |
ITEM-4 |   |   | 1

这个过程是动态的,读取 jSON 响应。我正在尝试像下面的示例一样执行此操作,但这是不正确的。

#get information of resultID
url = '<URL INVOKED>'
respResult = requests.get(url,headers=headers).json()

#add a new column to the dataframe
dataframe[respResult['name']] = ""

#get elements of the result
url = '<URL INVOKED>'
respElements = requests.get(url,headers=headers).json()

#populate the dataframe with the elements and their values    

for element in respElements:

    #get the values of the element
    url = '<URL INVOKED'
    respElementValues = requests.get(url,headers=headers).json()

    if(element['name'] in df.index):
        dataframe.loc[[element['name']],[respResult['name']]] = respElementValues['valueElement']
    else:
        #THIS BLOCK DOES NOT WORK
        dataframe.loc[len(dataframe)] = element['name'];
        dataframe.loc[[element['name']],[respResult['name']]] = respElementValues['valueElement'] #here the script returns the error "return_values_from_object(indexer) KeyError: ['ITEM-4'] not in index"

最佳答案

试试这个:

dataframe.loc[element['name'],respResult['name']] = respElementValues['valueElement']

通过从 element['name'] 中删除 []

关于python - 如何为现有的 pandas 数据框添加新的索引行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52433501/

相关文章:

python - 从 pandas 数据框转换为 LabeledPoint RDD

python - Pandas:没有排序索引和列的数据透视表

Python - 在数据框中运行 for 循环的更快方法

python - 从源代码安装时,使用 Python 3 和 Windows 安装 Spacy for NLP 会出现错误

python - XlsxWriter 将日期写入数字

python - 给定大小为 n 的矩阵,计算距中心的距离矩阵

python - python pandas中是否有countifs函数

python - 将 django ORM 与多处理一起使用?

python - 如何在Python中将pandas数据框转换为矩阵格式?

python - 如何使用 groupby 计算数据框中先前使用的产品数量?