How to Multiply array without numpy and math in pandas csv file - python

Halo, im sabil and newbie using python
First of all, i want to multiplle array with index:
[90,20] with [20,7]
My mentor ask me to not using anything library like (dot,add,etc) but using array
Here is my codefor transpose() :
def nilaiWeightTranspose():
nilaiWTranspose = jumlahBobot
x,y = jumlahBobot.shape
hasil = np.zeros((y,x))
for i in range(y):
for j in range(x):
hasil[i,j] = jumlahBobot.iloc[j,i]
hasilTranspose = pd.DataFrame(data = hasil[0:,0:])
return hasilTranspose
and output :
and here is my code for datanormalisasi():
def minmaxnormalization_latih(dropdata):
minperfeature = []
maxperfeature = []
datanormalisasilatih = datalatih
for i in range(len(dropdata.columns)):
minperfeature.append(min(dropdata[dropdata.columns[i]]))
maxperfeature.append(max(dropdata[dropdata.columns[i]]))
for i in range(len(datalatih.index)):
for j in range(len(datalatih.columns)):
datanormalisasilatih.loc[i, datalatih.columns[j]] = (datanormalisasilatih.loc[i, datalatih.columns[j]] - minperfeature[j]) / (maxperfeature[j] - minperfeature[j])
return datanormalisasilatih
and here is my code if i using library(dot) and succesful :
def nilaiHinit():
hitung_hInit = pd.DataFrame(datanormalisasilatih.values.dot(hasilTranspose.values), columns=jumlahBias.columns)
hitung_hInit_bias = hitung_hInit
the problem is idk how to multiple array without (dot) and i want to multiple array without (dot) or anything, can anyone know how to solve it?
thank you ^^

Related

List of Lists of Coordinates

I am new to Python, and am struggling with a task that I assume is an extremely simple one for an experienced programmer.
I am trying to create a list of lists of coordinates for different lines. For instance:
list = [ [(x,y), (x,y), (x,y)], [Line 2 Coordinates], ....]
I have the following code:
masterlist_x = list(range(-5,6))
oneline = []
data = []
numberoflines = list(range(2))
i = 1
for i in numberoflines:
slope = randint(-5,5)
y_int = randint(-10,10)
for element in masterlist_x:
oneline.append((element,slope * element + y_int))
data.append(oneline)
The output of the variable that should hold the coordinates to one line (oneline) holds two lines:
Output
I know this is an issue with the outer looping mechanism, but I am not sure how to proceed.
Any and all help is much appreciated. Thank you very much!
#khuynh is right, you simply had the oneline = [] in wrong place, you put all the coords in one line.
Also, you have a couple unnecessary things in your code:
you don't need list() the range(), you can just iterate them directly with for
also you don't need to declare the i for the for, it does it itself
that i is not actually used, which is fine. Python convention for unused variables is _
Fixed version:
from random import randint
masterlist_x = range(-5,6)
data = []
numberoflines = range(2)
for _ in numberoflines:
oneline = []
slope = randint(-5,5)
y_int = randint(-10,10)
for element in masterlist_x:
oneline.append((element,slope * element + y_int))
data.append(oneline)
print(data)
Also on-line there where you can run it: https://repl.it/repls/GreedyRuralProduct
I suspect the whole thing could be also made with much less code, and in a way in a simpler fashion, as a list comprehension ..
UPDATE: the inner loop is indeed very suitable for a list comprehension. Maybe the outer could be made into one as well, and the whole thing could two nested list comprehensions, but I only got confused when tried that. But this is clear:
from random import randint
masterlist_x = range(-5,6)
data = []
numberoflines = range(2)
for _ in numberoflines:
slope = randint(-5,5)
y_int = randint(-10,10)
oneline = [(element, slope * element + y_int)
for element in masterlist_x]
data.append(oneline)
print(data)
Again on repl.it too: https://repl.it/repls/SoupyIllustriousApplicationsoftware

Create arrays of fixed size within a while loop in python

I am trying to create arrays of fixed size within a while loop. Since I do not know how many arrays I have to create, I am using a loop to initiate them within a while loop. The problem I am facing is, with the array declaration.I would like the name of each array to end with the index of the while loop, so it will be later useful for my calculations. I do not expect to find a easy way out, however it would be great if someone can point me in the right direction
I tried using arrayname + str(i). This returns the error 'Can't assign to operator'.
#parse through the Load vector sheet to load the values of the stress vector into the dataframe
Loadvector = x2.parse('Load_vector')
Lvec_rows = len(Loadvector.index)
Lvec_cols = len(Loadvector.columns)
i = 0
while i < Lvec_cols:
y_values + str(i) = np.zeros(Lvec_rows)
i = i +1
I expect arrays with names arrayname1, arrayname2 ... to be created.
I think the title is somewhat misleading.
An easy way to do this would be using a dictionary:
dict_of_array = {}
i = 0
while i < Lvec_cols:
dict_of_array[y_values + str(i)] = np.zeros(Lvec_rows)
i = i +1
and you can access arrayname1 by dict_of_array[arrayname1].
If you want to create a batch of arrays, try:
i = 0
while i < Lvec_cols:
exec('{}{} = np.zeros(Lvec_rows)'.format(y_values, i))
i = i +1

Can I write python code that modifies itself during execution?

I mean,
target_ZCR_mean = sample_dataframe_summary['ZCR'][1]
target_ZCR_std = sample_dataframe_summary['ZCR'][2]
lower_ZCR_lim = target_ZCR_mean - target_ZCR_std
upper_ZCR_lim = target_ZCR_mean + target_ZCR_std
target_RMS_mean = sample_dataframe_summary['RMS'][1]
target_RMS_std = sample_dataframe_summary['RMS'][2]
lower_RMS_lim = target_RMS_mean - target_RMS_std
upper_RMS_lim = target_RMS_mean + target_RMS_std
target_TEMPO_mean = sample_dataframe_summary['Tempo'][1]
target_TEMPO_std = sample_dataframe_summary['Tempo'][2]
lower_TEMPO_lim = target_TEMPO_mean - target_TEMPO_std
upper_TEMPO_lim = target_TEMPO_mean + target_TEMPO_std
target_BEAT_SPACING_mean = sample_dataframe_summary['Beat Spacing'][1]
target_BEAT_SPACING_std = sample_dataframe_summary['Beat Spacing'][2]
lower_BEAT_SPACING_lim = target_BEAT_SPACING_mean - target_BEAT_SPACING_std
upper_BEAT_SPACING_lim = target_BEAT_SPACING_mean + target_BEAT_SPACING_std
each block of four lines of code are very similar to each other except for a few characters.
Can I write a function, a class or some other piece of code, such that I can wrap just a template of four lines of code into it and let it modify itself during runtime to get the code do the work of the above code...?
By the way, I use python 3.6.
If you find yourself storing lots of variables like this, especially if they are related, there is almost certainly a better way of doing it. Modifying the source dynamically is never the solution. One way is to use a function to keep the repeated logic, and use a namedtuple to store the resultant data:
import collections
Data = collections.namedtuple('Data', 'mean, std, lower_lim, upper_lim')
def get_data(key, sample_dataframe_summary):
mean = sample_dataframe_summary[key][1]
std = sample_dataframe_summary[key][2]
lower_lim = mean - std
upper_lim = mean + std
return Data(mean, std, lower_lim, upper_lim)
zcr = get_data('ZCR', sample_dataframe_summary)
rms = get_data('RMS', sample_dataframe_summary)
tempo = get_data('Tempo', sample_dataframe_summary)
beat_spacing = get_data('Beat Spacing', sample_dataframe_summary)
then you can access the data with the . notation like zcr.mean and tempo.upper_lim

Double for loop vs np.fromfunction(), why do they give different result in my case? [duplicate]

This question already has answers here:
Returned dtype of numpy vectorized function
(2 answers)
Closed 4 years ago.
while trying to program something I've come to need to create a 2D array(matrix) from a function that takes matrix indices (i and j in below example) as arguments and returns the matrix element.
I've seen from other answers that numpy.fromfunction() along with numpy.vectorize() should do the trick, however in my case those two seem to give a different result, what could be wrong?
More specifically I am comparing this:
for i in range(velikost):
for j in range(velikost):
u[i][j] = pomozna(i,j)
return u
to this(which I thought is equivalent to the above):
return np.fromfunction(np.vectorize(pomozna),u.shape)
Below is my full code, if you wish to run it by yourself. Any help appreciated, thanks!
import numpy as np
def jacobi(u,h,q):
velikost = u[0].size
star = np.copy(u)
def pomozna(i,j):
if i==0 or i==velikost-1 or j==0 or j==velikost-1:
return 0
return 1/4*(star[int(i+1)][int(j)]+star[int(i-1)][int(j)]+star[int(i)][int(j+1)]+star[int(i)][int(j-1)] - h*h*q[int(i)][int(j)])
#return np.fromfunction(np.vectorize(pomozna),u.shape)
for i in range(velikost):
for j in range(velikost):
u[i][j] = pomozna(i,j)
return u
h=0.05
iksi = np.linspace(0,1,int(1/h))
ipsiloni = np.linspace(0,1,int(1/h))
qji = [[-1 for iks in iksi] for ips in ipsiloni]
zacetna = np.asarray([[1.0 for iks in iksi] for ips in ipsiloni])
zacetna[0] = np.zeros(iksi.size)
zacetna[-1]=np.zeros(iksi.size)
zacetna[:,0] = np.zeros(iksi.size)
zacetna[:,-1] = np.zeros(iksi.size)
print(jacobi(zacetna,h,qji))
Perhaps try
return 0.0
in pomozna.

Translating matlab into python

I'm trying to translate a matlab code, and I'm strugeling to translate this part of the code:
[data;SS(ind-1:-1:ind-9)']
In the following context:
SS = 1:288
year = 1:288
data = [];
for ind = 10:length(year)
data = [data;SS(ind-1:-1:ind-9)'];
end
What I've done at the moment is:
SS = range(1,288);
year = range(1,288);
data = [];
for ind in range(10,length(year)):
data.append(######) # code to translate
EDIT: (Output Correction, wrong parameters)
1:288 is in python list(range(1,289)) or if you use numpy numpy.arange(1,289).
For index access you have to know, that matlab starts with 1, python with 0, so SS(ind-1:-1:ind-9) becomes SS[ind-2:ind-11:-1]
SS = list(range(1,289))
data = []
for ind in range(9,len(SS)):
data.append(SS[ind-9:ind][::-1])
or using numpy:
data = numpy.arange(9,0,-1)[None,:] + numpy.arange(279)[:, None]

Categories

Resources