简体   繁体   中英

How to structure a For loop with pandas dataframe

I have a csv file containing the below data

TSE/5216,"Kuramoto Co., Ltd. (5216)"
TSE/7235,"Tokyo Radiator Mfg. Co., Ltd. (7235)"
TSE/8016,"Onward Holdings Co., Ltd. (8016)"

I read it into a pandas dataframe

# The csv file that was downloaded doesnt come with headers, so I wrote it in using `names`
df = pandas.read_csv("file.csv", index_col=False, header=None, 
                     names=['Codes', 'Company Name'])

I am writing a for loop to download data from Quandl and saving it into a SQL.db file. I have the below code

for each_code in df['Codes']:
    get_prices = Quandl.get(each_code, returns='pandas')
    # Data to SQL
    get_prices.to_sql(name=each_code, con=engine')

My problem is that I want the name of the sql table to be the Company Name as shown in file.csv , instead of each_code . How should I structure my codes to do this?

You could use df.iterrows to iterate over the rows:

for idx, row in df.iterrows():
    get_prices = Quandl.get(row['Codes'], returns='pandas')
    # Data to SQL
    get_prices.to_sql(name=row['Company Name'], con=engine)

or use zip to pair df['Codes'] with df['Company Name'] :

for code, name in zip(df['Codes'], df['Company Name']):
    get_prices = Quandl.get(code, returns='pandas')
    # Data to SQL
    get_prices.to_sql(name=name, con=engine)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM