0

I have a 2D array "pop" in python. I want to multiply each element of column one with an integer. I used the following code

temp[i] = b*pop[i,0]+a*pop[i,1] 

But it is returning error "list indices must be integers or slices, not tuple"

jasonharper
  • 9,450
  • 2
  • 18
  • 42
gauss
  • 3
  • 1
  • 1
    There is no such thing as a "2D array" built in to Python. About the closest you can get using only standard data types is a list of lists, but in that case you have to index each level of list separately - references would look like `pop[i][0]`. – jasonharper Feb 09 '21 at 01:50
  • Have you looked into `numpy.array()`? – Reti43 Feb 09 '21 at 01:55
  • i am trying to read the data in a txt file into the array variable "pop". And I want to do computations on each variable of this array. I have used np.loadtext for doing that. – gauss Feb 09 '21 at 04:01
  • what does your two dimensional data table look like? what is the calculation to apply to the column? – Golden Lion Feb 09 '21 at 21:36

1 Answers1

0
import random
from random import sample
rows=20
a,b = 0.5,1 
pop=list(zip(sample(range(1, 100000), rows),sample(range(1, 100000), rows)))
profit = sample(range(1, 100000), rows)
#print(pop,profit)
mycombined=list(zip(pop,profit))
combined_array = np.asarray(mycombined)

print(combined_array)

m = len (combined_array) 
it = 1500 
#alpha = 0.01 

J=0
for i in range(1,m,1): 
     bpop=combined_array[i][0][0]
     apop=combined_array[i][0][1]
     aprofit=combined_array[i][1]
     temp=(bpop+apop-aprofit)**2
     J=J+temp

Now you have a list of lists and can use list comprehensions to change the values

  1. pop contains a two variable tuple
  2. profit is a list of random numbers
  3. the result is a list of lists or tuples
Golden Lion
  • 3,840
  • 2
  • 26
  • 35
  • I am having two arrays. Pop of dimension 96x2. I want each element of column 1 to be multiplied with value in b and column 2 with the value in a. The answer of each row calculation needs to be stored in temp. – gauss Feb 10 '21 at 09:57
  • import numpy as np a,b = 0.5,1 pop,profit = np.loadtxt('e:/python/gradientdescent/ex1data1.txt',delimiter = ",",unpack = True) m = len (profit) it = 1500 alpha = 0.01 pop = [np.ones(m),pop] for i in range(1,m,1): temp =( b*pop[i][0]+a*pop[i][1]-profit[i][0])**2 J = J+temp – gauss Feb 10 '21 at 10:06
  • will you provide a few rows from the gradientdecent data file – Golden Lion Feb 10 '21 at 12:23
  • I created a tuple list as pop and profit as a list of numbers and combined the tuple list with the profit list and demonstrated how to gain accessibility to the numbers using indexes – Golden Lion Feb 11 '21 at 18:03