遍历数据帧以填充API请求

2024-10-03 15:32:14 发布

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

我有一个dataframecomplete,我想遍历每一行并从列的内容构建一个API请求,每一行都是一个新的请求。你知道吗

我的请求正文必须如下所示:

body=
{
    'conversion' : [{
        'clickId' : complete['click_id'],
        'conversionId' : complete['conv_id'],
        'conversionTimestamp' : complete['timestamp'],
        'segmentationType' : complete['seg_type'],
        'type': complete['type'],
        'revenueMicros': complete['order_pro'],
        'quantityMillis': complete['quant_mic'],
      }]
}

到目前为止,我已经尝试了for循环,但我觉得这不能准确地工作:

  for row in complete:


request = service.conversion().update(
    body=
    {
        'conversion' : [{
            'clickId' : complete['click_id'],
            'conversionId' : complete['conv_id'],
            'conversionTimestamp' : complete['timestamp'],
            'segmentationType' : complete['seg_type'],
            'type': complete['type'],
            'revenueMicros': complete['order_pro'],
            'quantityMillis': complete['quant_mic'],
          }]
    }
)

print(body)
# request.execute()

我也尝试过使用iterrows()进行查找,但在测试时,我无法判断这是否保持了行结构。你知道吗

用数据帧中的列值一次一行填充循环的正确方法是什么?你知道吗


Tags: idtypeorderbodytimestampcompleteclickconversion
2条回答

您可以使用df.apply(func, axis=1)构建查询,然后执行它们。你知道吗

在处理数据帧时,我总是喜欢使用这种方法-我觉得遍历行是一件非常不容易的事情。。。但我不知道为什么我会有这种感觉。:)

例如

def build_request(row):
    return {
        'conversion' : [{
            'clickId' : row['click_id'],
            'conversionId' : row['conv_id'],
            'conversionTimestamp' : row['timestamp'],
            'segmentationType' : row['seg_type'],
            'type': row['type'],
            'revenueMicros': row['order_pro'],
            'quantityMillis': row['quant_mic'],
          }]
    }

request_bodies = complete.apply(build_request, axis=1).tolist()

然后遍历请求体

您需要用row替换complete并使用iterrows()

for row in complete.iterrows():
    request = service.conversion().update(
      body=
    {
        'conversion' : [{
            'clickId' : row['click_id'],
            'conversionId' : row['conv_id'],
            'conversionTimestamp' : row['timestamp'],
            'segmentationType' :row['seg_type'],
            'type': row['type'],
            'revenueMicros': row['order_pro'],
            'quantityMillis': row['quant_mic'],
          }]
    })    
    print(body)

相关问题 更多 >