Iterate through a dataframe to populate API requests

时间:2019-04-08 13:50:41

标签: python pandas

I have a dataframe complete and I would like to iterate through each row and build an API request from the contents of the columns, each row being a new request.

My request body must look like:

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'],
      }]
}

So far I have tried a for loop, but I don't feel like this will work accurately:

  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()

I've also tried a lookup with iterrows(), but when testing I can't tell if this is maintaining the row structure.

What is the correct way to populate a loop with column values from a dataframe, one row at a time?

2 个答案:

答案 0 :(得分:2)

you could use df.apply(func, axis=1) to build your queries, then execute them.

I've always preferred this as an approach when working with dataframes - i feel like iterating through rows is a very non-pandas thing to do... but I don't actually know why i feel that way. :)

eg

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()

then just iterate through request_bodies

答案 1 :(得分:2)

You need to replace complete with your row and use 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)