LaVOZs

The World’s Largest Online Community for Developers

'; python - Looping through pandas dataframe and assigning values - LavOzs.Com

This is probably a very stupid question but I have been searching for example on this site as well as others and I have yet to find an answer that works. I am trying to multiply two arrays and assign the values to a 2D array within nested loops.

I have two variable 'cars' and 'scrappage'. I would like to multiply each element wise and create a 2D array that is 10x10.

I was able to do this in MATLAB but I am new to python, so I know I am probably using the Pandas dataframe incorrectly. I have tried to debug the code, and everything runs exactly as it should (creation of data frames, loops, etc.) with the exception of the array multiplication and values being assigned to the 2D array.

I know this is an indexing error I keep receiving the "IndexError: single positional indexer is out-of-bounds" message.

Here is my code:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

cars = pd.DataFrame([1000,2000,3000,4000,5000,6000,7000,8000,9000,10000])
scrappage = pd.DataFrame([1,.95,.86,.75,.62,.44,.30,.20,.12,.04])
Fleet = pd.DataFrame([])

i=0
j=0

for i in range(0,len(cars)):
    for j in range(0,len(scrappage)):
        Fleet.iloc[i,j]= cars.iloc[i,0] * scrappage.iloc[j,0]
        #This^ line is causing the error.
        j= j+1
    i=i+1

I'm sure this is probably very simple for most but I am struggling with the Pandas syntax. Thank you in advance for any help.

Instead defining fleet as empty dataframe you should give it proper index and column. You can try this:-

import numpy as np
import pandas as pd

cars = pd.DataFrame([1000,2000,3000,4000,5000,6000,7000,8000,9000,10000])
scrappage = pd.DataFrame([1,.95,.86,.75,.62,.44,.30,.20,.12,.04])
fleet =  pd.DataFrame(index=range(len(cars)),columns=range(len(scrappage))) 

i=0
j=0

for i in range(0,len(cars)):
    for j in range(0,len(scrappage)):
        fleet.iloc[i,j]= cars.iloc[i,0] * scrappage.iloc[j,0]
        j= j+1
    i=i+1
Related
Accessing the index in 'for' loops?
How do I sort a dictionary by value?
Iterating over dictionaries using 'for' loops
Selecting multiple columns in a pandas dataframe
Renaming columns in pandas
Adding new column to existing DataFrame in Python pandas
Delete column from pandas DataFrame
How to iterate over rows in a DataFrame in Pandas?
How to select rows from a DataFrame based on column values?
Get list from pandas DataFrame column headers