在DataFrame上迭代以将数据传递到API

2024-05-20 18:46:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个脚本,读取GoogleSheet,转换数据并将其传递到我的ERP API中,以自动创建采购订单

我已经在数据帧中输出了数据,但是我需要关于如何迭代并以正确的格式将其传递给API的帮助

数据帧示例(dfRow):

   productID  vatrateID  amount  price
0      46771          2       1   1.25
1      46771          2       1   2.25
2      46771          2       2   5.00

API数据的格式:

              vatrateID1=dfRow.vatrateID[0],
              amount1=dfRow.amount[0],
              price1=dfRow.price[0],
              productID1=dfRow.productID[0],
              vatrateID2=dfRow.vatrateID[1],
              amount2=dfRow.amount[1],
              price2=dfRow.price[1],
              productID2=dfRow.productID[1],
              vatrateID3=dfRow.vatrateID[2],
              amount3=dfRow.amount[2],
              price3=dfRow.price[2],
              productID3=dfRow.productID[2],

我想创建一个函数来遍历DataFrame并以正确的格式返回数据以传递给API

我是Python新手,在迭代/循环方面最为困难,所以非常感谢您的帮助


Tags: 数据订单脚本api示例erp格式amount
1条回答
网友
1楼 · 发布于 2024-05-20 18:46:23

首先,您可以始终使用df.iterrows()在数据帧的行上循环。通过该迭代器的每一步都会生成一个元组,其中包含行索引和行内容作为一个对象。举个例子,这就可以做到:

for ix, row in df.iterrows():
    for column in row.index:
       print(f"{column}{ix}={row[column]}")

您也可以不使用循环来完成。如果您需要性能,这是很好的,但是如果性能不是一个问题,那么它实际上只是一个品味的问题

# first, "melt" the data, which puts all of the variables on their own row
x = df.reset_index().melt(id_vars='index')

# now join the columns together to produce the rows that we want
s = x['variable'] + x['index'].map(str) + '=' + x['value'].map(str)

print(s)

0     productID0=46771.0
1     productID1=46771.0
2     productID2=46771.0
3         vatrateID0=2.0
...
10           price1=2.25
11            price2=5.0

相关问题 更多 >