How To Put Values Of Pandas Dataframe Into A For Loop In Python?
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 4
Solution 1:
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={'StartDate':'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)regionsectorbrandidscoringstart_dateend_date7188 US4140000total2006-03-06 2020-03-317189 US4140345total2017-11-06 2020-03-317190 US4140123total2019-01-12 2020-03-317191 US4240145total2001-02-06 2020-03-317192 US4240185total2013-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'}
Solution 2:
Iterate the dataframe by rows using iterrows(). I believe your dataframe name is US. Then:
for(index, row_data) in US.iterrows():
querySingleBrandTimeline('db.csv', {'region':{}.format(row_data['Region']),'sector':{}.format(row_data['Category ID']), 'brand_id':{}.format(row_data['Brand ID']), 'scoring':'total'}, 'start_date':{}.format{row_data['Start Date']},'end_date':'2020-03-31'})
Solution 3:
Edit:Jezrael's approach is much better for what you want to do though.
To iterate through a pandas data frame by rows you can use pandas.DataFrame.iterrows
import pandas as pd
df = pd.DataFrame({
'col1':[1,5,3,54,34,56,45],
'col2':['foo','bar','foo','foo','bar','foo','foo'],
'col3':[True,True,False,True,True,False,True]})
for idx, row in df.iterrows():
if row['col3']:
print('\n'+str(idx))
print(row['col2']+'_'+str(row['col1']))
Output:
0
foo_1
1
bar_5
3
foo_54
4
bar_34
6
foo_45
Post a Comment for "How To Put Values Of Pandas Dataframe Into A For Loop In Python?"