How to put values of pandas dataframe into a for loop in python?

2024/10/11 6:34:45

This is a part of a Python API Connection program

Here is the DataFrame Sample

      Region  Sector  Brand ID  Start Date
7188  US      41      40000     2006-03-06
7189  US      41      40345     2017-11-06
7190  US      41      40123     2019-01-12
7191  US      42      40145     2001-02-06
7192  US      42      40185     2013-03-16

Here is the working function as a part of API python program which usually takes a fixed parameter values i.e; Region, Sector, Brand ID, Start Date, End Date="05-04-2020", Scoring ="total".(End Date and Scoring are fixed values, rest of them are keep changing).

#This code is working if manually enter
#details of a Dataframe one by one which is inefficient.
#This code generates me a URL of a dataset using the parametersquerySingleBrandTimeline('db.csv', {'region':'us','sector':'41', 'brand_id':'40000', 'scoring':'total', 'start_date':'2006-03-06','end_date':'2020-03-31'})

What I am trying to achieve is a for loop which takes values from the pandas DtaFrame and put it in the function parameters accordingly.

Here is the sample code i've tried:

for id in US['Sector']:for brandid in US['Brand ID']:querySingleBrandTimeline('db.csv', {'region':{}.format(US['Region']),'sector':{}.format(US['Category ID']), 'brand_id':{}.format(US['Brand ID']), 'scoring':'total'}, 'start_date':{}.format{US['Start Date']},'end_date':'2020-03-31'})

I'm quite not sure how to pass values of the DataFrame to the function dynamically

Answer

I think iterrows here is not necessary, because slowiest iterate solution in pandas (and output is Series, here are necessary dicts).

First add scalar columns to DataFrame and rename columns names:

df1 = df.rename(columns={'Start Date':'start_date'}).rename(columns=str.lower)
df1.insert(3, 'scoring', 'total')
df1['end_date'] = '2020-03-31'
df1['start_date'] = df1['start_date'].dt.strftime('%Y-%m-%d')print (df1)region  sector  brand id scoring  start_date    end_date
7188     US      41     40000   total  2006-03-06  2020-03-31
7189     US      41     40345   total  2017-11-06  2020-03-31
7190     US      41     40123   total  2019-01-12  2020-03-31
7191     US      42     40145   total  2001-02-06  2020-03-31
7192     US      42     40185   total  2013-03-16  2020-03-31

And then convert to list of dicts by DataFrame.to_dict and loop:

for d in df1.to_dict('record'):print (d){'region': 'US', 'sector': 41, 'brand id': 40000, 'scoring': 'total', 'start_date': '2006-03-06', 'end_date': '2020-03-31'}
{'region': 'US', 'sector': 41, 'brand id': 40345, 'scoring': 'total', 'start_date': '2017-11-06', 'end_date': '2020-03-31'}
{'region': 'US', 'sector': 41, 'brand id': 40123, 'scoring': 'total', 'start_date': '2019-01-12', 'end_date': '2020-03-31'}
{'region': 'US', 'sector': 42, 'brand id': 40145, 'scoring': 'total', 'start_date': '2001-02-06', 'end_date': '2020-03-31'}
{'region': 'US', 'sector': 42, 'brand id': 40185, 'scoring': 'total', 'start_date': '2013-03-16', 'end_date': '2020-03-31'}
https://en.xdnf.cn/q/118354.html

Related Q&A

Partition Array

Given an array nums of integers and an int k, partition the array (i.e move the elements in nums) such that: All elements < k are moved to the left. All elements >= k are moved to the right Retur…

Tensorflow model accuracy

My model which I have trained on a set of 29K images for 36 classes and validated on 7K images. The model has a training accuracy of 94.59% and validation accuracy of 95.72% It has been created for OCR…

python email.message_from_string() parse problems

My setup uses fetchmail to pull emails from Gmail, which are processed by procmail and passes it to a python script.When I use email.message_from_string(), the resulting object is not parsed as an emai…

Python: Function returning highest value in list without max()? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 7…

Given edges, how can find routes that consists of two edges in a vectorised way?

I have an array of towns and their neighbours. I want to get a set all the pairs of towns that have at least one route that consists of exactly two different edges. Is there a vectorized way to do this…

Usefulness of one-line statements in Python [closed]

Closed. This question is opinion-based. It is not currently accepting answers.Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.Clo…

Pack data into binary string in Python [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

Parsing Complex Mathematical Functions in Python

Is there a way in Python to parse a mathematical expression in Python that describes a 3D graph? Using other math modules or not. I couldnt seem to find a way for it to handle two inputs.An example of…

How do I check if the user has entered a number? [duplicate]

This question already has answers here:How can I read inputs as numbers?(10 answers)Closed last year.I making a quiz program using Python 3. Im trying to implement checks so that if the user enters a …

high F1 score and low values in confusion matrix

consider I have 2 classes of data and I am using sklearn for classification, def cv_classif_wrapper(classifier, X, y, n_splits=5, random_state=42, verbose=0):cross validation wrappercv = StratifiedKFol…