write python program to add list,the first list is a 10*3*11 list(3 dimension), and the second list is also a 10*3*11 list with all elements are 0, add them,use numpy:
data_split_count = 10
cluster_number = 3
total_center_list = [[[[0] for i in range(11)] for j in range(cluster_number)] for kj in range(data_split_count)]
print("1 len total center list")
print(len(total_center_list))
total_center_data_list = minibatchkmeansClustering_no_gender(data_list)
print("total center list")
print(len(total_center_data_list))
print("total center list 0")
print(len(total_center_data_list[0]))
print("total center list 0 0")
print(len(total_center_data_list[0][0]))
print(total_center_data_list[0][1])
print("sum total center list")
temp_test = numpy.array([total_center_data_list,total_center_list])
total_center_list = temp_test.sum(axis = 0)
print(len(total_center_list))
when runnung, it shows:
1 len total center list
10
total center list
10
total center list 0
3
total center list 0 0
11
[ 0.07459313 0.05333272 0.01219305 0.32307944 0.16194127 0.00409273
0.34603601 0.33625275 0.06253664 0.1693817 0.08579227]
sum total center list
File "F:/MyDocument/F/My Document/Training/Python/PyCharmProject/FaceBookCrawl/FB_group_user_stability.py", line 36, in dist_cal
temp_test = numpy.array([total_center_data_list,total_center_list])
ValueError: setting an array element with a sequence
could you please tell me the reason and how to solve it
If you would like to use numpy, it operates on arrays of data. You have to convert your lists to arrays using asarray. Then you can just add two arrays together element-wise, using "+".
import numpy as np
list1=range(3*5*11) # list1 = your total_center_list
a1=np.asarray(list1).reshape((3,5,11)) # converted to numpy array, reshaped to match your dimensions
print a1
list2=range(3*5*11) # list2 = your total_center_data_list
a2=np.asarray(list2).reshape(3,5,11)
a3=a1+a2 # your sum array
print a3.shape # checks dimensions
Related
I have an array 'aN' with a shape equal to (1000,151). I need to calculate the average every 10 data in rows, so I implemented this
arr = aN[:]
window_size = 10
i = 0
moving_averages = []
while i < len(arr) - window_size + 1:
window_average = round(np.sum(arr[i:i+window_size]) / window_size, 2)
moving_averages.append(window_average)
i += 10
The point is that my output is a list of 100 data, but I need an array with the same number of columns that the original array (151).
Any idea on how to get this outcome??
TIA!!
If you convert it to a pandas dataframe, you can use the rolling() function of pandas together with the mean() function. It should be able to accomplish what you need.
I'm attempting to write python code to solve a transportation problem using the Least Cost method. I have a 2D numpy array that I am iterating through to find the minimum, perform calculations with that minimum, and then replace it with a 0 so that the loops stops when values matches constantarray, an array of the same shape containing only 0s. The values array contains distances from points in supply to points in demand. I'm currently using a while loop to do so, but the loop isn't running because values.all() != constantarray.all() evaluates to False.
I also need the process to repeat once the arrays have been edited to move onto the next lowest number in values.
constarray = np.zeros((len(supply),len(demand)) #create array of 0s
sandmoved = np.zeros((len(supply),len(demand)) #used to store information needed for later
totalcost = 0
while values.all() != constantarray.all(): #iterate until `values` only contains 0s
m = np.argmin(values,axis = 0)[0] #find coordinates of minimum value
n = np.argmin(values,axis = 1)[0]
if supply[m] > abs(demand[m]): #all demand numbers are negative
supply[m]+=demand[n] #subtract demand from supply
totalcost +=abs(demand[n])*values[m,n]
sandmoved[m,n] = demand[n] #add amount of 'sand' moved to an empty array
values[m,0:-1] = 0 #replace entire m row with 0s since demand has been filled
demand[n]=0 #replace demand value with 0
elif supply[m]< abs(demand[n]):
demand[n]+=supply[m] #combine positive supply with negative demand
sandmoved[m,n]=supply[m]
totalcost +=supply[m]*values[m,n]
values[:-1,n]=0 #replace entire column with 0s since supply has been depleted
supply[m] = 0
There is an additional if statement for when supply[m]==demand[n] but I feel that isn't necessary. I've already tried using nested for loops, and so many different syntax combinations for a while loop but I just can't get it to work the way I want it to. Even when running the code block over over by itself, m and n stay the same and the function removes one value from values but doesn't add it to sandmoved. Any ideas are greatly appreciated!!
Well, here is an example from an old implementation of mine:
import numpy as np
values = np.array([[3, 1, 7, 4],
[2, 6, 5, 9],
[8, 3, 3, 2]])
demand = np.array([250, 350, 400, 200])
supply = np.array([300, 400, 500])
totCost = 0
MAX_VAL = 2 * np.max(values) # choose MAX_VAL higher than all values
while np.any(values.ravel() < MAX_VAL):
# find row and col indices of min
m, n = np.unravel_index(np.argmin(values), values.shape)
if supply[m] < demand[n]:
totCost += supply[m] * values[m,n]
demand[n] -= supply[m]
values[m,:] = MAX_VAL # set all row to MAX_VAL
else:
totCost += demand[n] * values[m,n]
supply[m] -= demand[n]
values[:,n] = MAX_VAL # set all col to MAX_VAL
Solution:
print(totCost)
# 2850
Basically, start by choosing a MAX_VAL higher than all given values and a totCost = 0. Then follow the standard steps of the algorithm. Find row and column indices of the smallest cell, say m, n. Select the m-th supply or the n-th demand whichever is smaller, then add what you selected multiplied by values[m,n] to the totCost, and set all entries of the selected row or column to MAX_VAL to avoid it in the next iterations. Update the greater value by subtracting the selected one and repeat until all values are equal to MAX_VAL.
Here's the full question: Create an array to store 5 random integers between 1 and 40. Print the sum and average of all elements in the given array. Finally, print the array backward!
Here's what I have so far:
import random
print("12 random numbers between 5 and 50")
randNumbers = random.randint(5, 50)
num1=randNumbers(1)
print(num1)
randNumbers.reverse()
for element in randNumbers:
print(element)
sum=sum+nums
avg=(round(sum/n,3))
if (nums%2==0):
even+=1
else:
odd+=1
print("\nSum: ",sum)
print("Average: ",round(avg,1))
I'm new to coding and I'm not really sure how to fix it. I'd appreciate any help!
Based off of your written prompt, here is a solution:
import random
# five rand int between 1 and 40
randNumbers = [random.randint(1, 40) for _ in range(5)]
print(randNumbers)
# print sum stored in randNumbers
print(sum(randNumbers))
# print avg stored in randNumbers
print(sum(randNumbers)/len(randNumbers))
# print array backwards
print(randNumbers[::-1])
This is the answer to the question in text, however it doesn't match your code so hopefully, this is what you wanted.
import random
print("12 random numbers between 5 and 50")
randNumbers = []
for i in range(0, 12):
randNumbers.append(random.randint(1, 40))
print("Original: " + str(randNumbers))
print("Sum: " + str(sum(randNumbers)))
print("Average: " + str(sum(randNumbers) / len(randNumbers)))
randNumbers.reverse()
print("Reversed: " + str(randNumbers))
Long and detailed answer
import random
print("12 random numbers between 5 and 50")
randNumbers = [] # initialize an empty array
for i in range(5): # create 5 times..
randNum = random.randint(1, 40) # ..a random number between 1 and 40
randNumbers.append(randNum) # then add it to the array
print(f"array is {randNumbers}")
# Print sum of the elements of array
s = 0 # initialize the sum s to 0
for element in randNumbers:
s = s + element # add each element of the array to the sum s
print(f"sum is {s}")
# Print the average
size = len(randNumbers) # the size of the array
average = s / size # the average of the array
print(f"average is {average}")
# Print the array backwards
backed = []
for i in range(1, size+1):
backed.append(randNumbers[-i])
print(f"backward array is{backed}")
Short answer:
import random
randNumbers = [random.randint(1, 40) for i in range(5)]
print(f"array is {randNumbers}")
s = sum(randNumbers)
print(f"sum is {s}")
avg = s / len(randNumbers)
print(f"average is {avg}")
backed = list(reversed(randNumbers))
print(f"backward array is{backed}")
I highly recommend you to use numpy library for all these mathematical operations.
Code:
import numpy as np
rand_nums = np.random.randint(1,40,5)
print(f"Random integer array: {rand_nums}")
print(f"Sum: {rand_nums.sum()}")
print(f"Average: {rand_nums.mean()}")
print(f"Backwards array: {rand_nums[::-1]}")
I'm trying to create and an array of shape (1, inter) [i.e. 1 row, inter Columns], where inter is user input;
If you look at the code below,
l_o_s, Inter, n_o_s, L, d_o_s are all from user inputs
The n_o_s represents the number of sections across the total length of the shaft that have lengths corresponding to the values in l_o_s and diameters corresponding to the values in d_o_s.
So
Section 1 has a length of 1.5 and diameter 3.75
Section 2 = length of 4.5-1.5 = 3 and diameter 3.5
Section 3 = length of 7.5-4.5 = 3 and diameter 3.75
and so forth...
Here's an image of the shaft arrangement:
This is a shaft of length = 36, with 13 sections that have different size diameters
Inter is the number of intervals I require in the analysis, in this case inter is 3600, so I require a (1,3600) array.
si is an array that is a function (mathematical) of the length of the individual section in l_o_s, the total length (L) of the system and the interval (Inter).
Here's the question
So if you take every value in
si = [ 150. 450. 750. 1050. 1350. 1650. 1950. 2250. 2550. 2850. 3150. 3450. 3600.]
I require an array of shape (1,3600) whose first 150 elements are all equal to the diameter of section 1 - (3.75), and the elements between 150 and 450 i need them to equal the diameter of the second section (3.5) and so forth...
So i need the first 150 element corresponding to index 0 in d_o_s and the next 300 elements corresponding to index 1 in d_o_s, etc...
Here's a code I began with, but I don't think it's worth talking about. I was creating an array of zeros with inner inner shapes corresponding to each of the 150,300,300,300 elements.
import numpy as np
import math
L = 36
Inter = 3600
n_o_s = 13
l_o_s = np.asarray([1.5,4.5,7.5,10.5,13.5,16.5,19.5,22.5,25.5,28.5,31.5,34.5,36])
d_o_s = np.asarray([3.75,3.5,3.75,3.5,3.75,3.5,3.75,3.5,3.75,3.5,3.75,3.5,3.75])
si = np.asarray((l_o_s/L)*Inter)
print(si)
z = (si.size)
def f(x):
for i in si:
zz = np.zeros((x,1,int(i)))
for j in range(int(z)):
for p in range(int(d_o_s[j])):
zz[j][0][p] = np.full((1,int(i)),(math.pi*d_o_s**4)/64)
return zz
print(f(z))
Any ideas,
Dallan
This is what I ended up with but I'm only receiving 3599 values instead of the required 3600 any ideas? I used the diameter to output another variable (basically swapped the diameters in d_o_s for values in i_o_s)
L = 36
Inter = 3600
n_o_s = 13
l_o_s = np.asarray([0,1.5,4.5,7.5,10.5,13.5,16.5,19.5,22.5,25.5,28.5,31.5,34.5,36])
d_o_s = np.asarray([3.75,3.5,3.75,3.5,3.75,3.5,3.75,3.5,3.75,3.5,3.75,3.5,3.75])
i_o_s = (math.pi*d_o_s**4)/64
si = np.asarray((l_o_s/L)*Inter)
lengths = si[1:] - si[:-1]
Iu = np.asarray(sum([[value]*(int(length)) for value, length in zip(i_o_s, lengths)], []))
print(Iu,Iu.shape)
In python, an operation like 4 *[1] produces [1,1,1,1]. So, you need to calculate the lengths of the subarrays, create them, and concatenate them using sum().
lengths = si[1:] - si[:-1]
result = sum([
[value]*length for value, length in zip(d_o_s, lengths)
], [])
Also, your si array is of type float, so you get a rounding error when used as index. convert it to integer, by changing
si = np.asarray((l_o_s/L)*Inter)
to
si = np.asarray((l_o_s/L)*Inter).astype(int)
My question
1. Intro
ka & kb are two 2-d array all in the shape of 31*37
They contain 2 value: 0 & 1
Independence:the grid amount when only the value of ka[i, j] = 1
Using np.mask, they shows like this:
http://i4.tietuku.com/29adccd90484fe34.png
code here:
ka_select = np.ma.masked_less(ka,0.001)
pa =plt.pcolor(kb_select,cmap="Set1",alpha =0.7,facecolor = "k",edgecolor = 'k',zorder =1)
kb_select = np.ma.masked_less(kb,0.001)
pb =plt.pcolor(kb_select,cmap="Set1",alpha =0.7,facecolor = "k",edgecolor = 'k',zorder =1)
2. My early work
Comparing with two array ka & kb.
If the value in index[i,j] all equal to 1, it means that this two array has overlapped in this grid.
Count the overlapping frequency.
I have written some code about comparing two 2-d array
### repeat I defined is the estimate matrix to represent overlap or not in [i,j] position
repeat = np.zeros(ka.shape[0]*ka.shape[0]).reshape(ka.shape[0],ka.shape[1])
for i in range(0,ka.shape[0],1):
for j in range(0,ka.shape[1],1):
if (ka[i,j] == 1) & (kb[i,j] == 1) :
repeat [i,j]=1
else:
repeat[u,v] = 0
rep.append(repeat.sum())
rep: the overlapping frequency for these two 2-d array.
http://i4.tietuku.com/7121ee003ce9d034.png
3. My question
When there are more than two 2-d numpy array all in the same shape with value (0,1), How to sum the overlapping frequency?
I can compare multi array in sequence but the repeat grid would be re-counted
More explain
I want to sum the amount of array ka when ka = 1 but (kb & kc & ...) != 1 at grid[i,j] (Which I call it independence as shown in title).
If ka only comparing with kb, I can use rep to achieve that, and I haven't thought out the method dealing with more than 2 array
Why not using the sum of the arrays kb, ... and test the resulting elements?
An example with three grids:
import numpy
# some random arrays
ka = numpy.random.random_integers(0,1,37*31).reshape(31,37)
kb = numpy.random.random_integers(0,1,37*31).reshape(31,37)
kc = numpy.random.random_integers(0,1,37*31).reshape(31,37)
combined_rest = kb + kc
print "independance:", numpy.sum( (ka == 1) & (combined_rest < 2) )