2

Suppose i have a loop structure that looks like the following:

numlist = [0.1, 0.25, 0.5, 0.75, 0.90, 1.1, 1.25, 1.5]
numlist = np.array(numlist,dtype=float)
apcnt = np.zeros((4,8))
for x in range(5):
   for y in numlist:
     apcnt[x][y] = a.iloc[x][0]*numlist[y]
     print(apcnt)

Dataframe "a" looks like this:

           adjusted_power
YearMonth                
Q1           19388.321839
Q2           13435.865517
Q3           12579.123793
Q4           19238.458966 

and I'm trying to obtain a final answer that looks like this:

YearMonth
Q1           19388*0.1   19388*0.25  19388*0.50  19388*0.75  19388*0.9   19388*1.1  19388*1.25  
19388*1.5
Q2           13436(same as above for Q1 example)
Q3           12579(same as above for Q1 example)
Q4           19238(same as above for Q1 example)

I get an index error in this form ( thank you for your help):

File "<ipython-input-40-e72f79d55da3>", line 7, in <module>
apcnt[x][y] = a.iloc[x][0]*numlist[y]

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or 
boolean arrays are valid indices

2 Answers 2

2

We can do multiply.outer

pd.DataFrame(np.multiply.outer(a['adjusted_power'].values,numlist),index=a.index)
                     0            1  ...             6             7
YearMonth                            ...                            
Q1         1938.832184  4847.080460  ...  24235.402299  29082.482759
Q2         1343.586552  3358.966379  ...  16794.831896  20153.798275
Q3         1257.912379  3144.780948  ...  15723.904741  18868.685690
Q4         1923.845897  4809.614741  ...  24048.073707  28857.688449
[4 rows x 8 columns]
Sign up to request clarification or add additional context in comments.

Comments

1

You can use broadcasting:

out = pd.DataFrame(a.adjusted_power.values[:,None] * numlist,
                   index=a.index)

Output:

          0        1        2         3        4        5        6        7
--  -------  -------  -------  --------  -------  -------  -------  -------
Q1  1938.83  4847.08  9694.16  14541.2   17449.5  21327.2  24235.4  29082.5
Q2  1343.59  3358.97  6717.93  10076.9   12092.3  14779.5  16794.8  20153.8
Q3  1257.91  3144.78  6289.56   9434.34  11321.2  13837    15723.9  18868.7
Q4  1923.85  4809.61  9619.23  14428.8   17314.6  21162.3  24048.1  28857.7

2 Comments

hi -thanks, it works great!! what is the meaning of the [: , None] after "values"?
Basically arr = np.array([1,2,3])[:,None] gives you [[1],[2],[3]] which then allows arr * [4,5]. More details here. you can also do np.multiply.outer([1,2,3], [4,5])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.