defining variables using a list of dataframes [duplicate] - python

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 3 years ago.
I have a list of dataframe variables:
B = [df1,df2,df3,df4]
I am running a for loop like below:
for element in B:
element + '_norm' = (element - element.mean())/ (element.max() -
element.min())
How do I write the variable name so that I may reference the normalized dataframe? That is to say I would like to be able to define the normalized dataframe 3 using the variable "df3_norm". How can I write the variable into the for loop so that the "df3_norm" format can be referenced?

Use dict:
df_dict = {}
for i, element in enumerate(B):
df_dict['df%i_norm' % i] = (element - element.mean())/(element.max() - element.min())
BTW, normalization involves subtracting min from elements not mean.
If you want normalization:
df_dict['df%i_norm' % i] = (element - element.min())/(element.max() - element.min())
# ^^^^^
Else if you want standardization:
df_dict['df%i_norm' % i] = (element - element.mean())/(element.std())

Related

Is it possible to modify the list itself, not its copy? [duplicate]

This question already has answers here:
How to modify list entries during for loop?
(10 answers)
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
I need to write a function which removes odd numbers from a list and square remaining even numbers.
I've tried something like this:
def modify_list(l):
l1 = [i ** 2 for i in l if i % 2 == 0]
return l1
but it creates a copy from a list that I've passed to a function, whereas I need to modify the passed list itself, so the following code would result:
id(l1) == id(l) # True
I've also tried to rewrite the code using remove method, but I couldn't figure out how to square remaining elements from passed list so it would return the same list (not its copy)
def modify_list(l):
for element in l:
if element % 2 != 0:
l.remove(element)
Is it possible to change my code in order to return the same list object that I've passed, but without odd numbers and with squared even numbers?
def modify_list(l):
li = [i**2 for i in l if i % 0 == 0]
for n,i in enumerate(li):
l[n] = i
return l
lists are mutable so a direct assignment works. 'li' is a new list so will have a different id.

did I did something wrong with list and for loop in python? [duplicate]

This question already has answers here:
Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add (append) elements to a list?
(9 answers)
Closed 1 year ago.
the thing that I am supposed to do is,
get 10 int
find the different value after doing %42 for those 10 input int
and what I thought is, like this
n = []
for i in range(10):
a = int(input())
n[i] = a%42
s = set(n)
print(len(s))
but it didn't work with a message of
----> 4 n[i] = a%42
IndexError: list assignment index out of range
and by googling I have solved this question by adding append.
n = []
for i in range(10):
a = int(input())
print("a",a)
b = a%42
print("b",b)
n.append(b)
s = set(n)
print(len(s))
** here is my question. why did my code didn't work? I thought my method's logic is solid. Is there some knowledge that I am missing about? **
thank you previously.
actually when you were trying first way you were using lists built-in dunder(magic method) which asks that there must be an element at that index before changing its value, meanwhile list is empty and hence it can't find an element whose value has to be chanced but append works something like this:
yourList += [newElement]
which is basically like list concatination.
Your code doesn't work because n is an empty list so it has no sense to assign a value to an index.
If you know the size of your list you can do:
# this works
n = [size]
n[0] = 1

How Pytorch Tensor get the index of elements? [duplicate]

This question already has answers here:
How Pytorch Tensor get the index of specific value
(10 answers)
Closed 3 years ago.
I have 2 Tensors named x and list and their definitions are below:
x = torch.tensor(3)
list = torch.tensor([1,2,3,4,5])
Now I want to get the index of element x from list. The expected output is an Integer:
2
How can I do in an easy way?
import torch
x = torch.tensor(3)
list = torch.tensor([1,2,3,4,5])
idx = (list == x).nonzero().flatten()
print (idx.tolist()) # [2]
list = torch.tensor([1,2,3,3,5])
idx = (list == x).nonzero().flatten()
print (idx.tolist()) # [2, 3]

How to create matrices with different names inside a for loop [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 6 years ago.
I want to create the matrices 1x5: matriz1, matriz2 and matriz3, with the values i + j, but my code doesn't work. Can someone help me?
import numpy as np
for i in range(3):
name= 'matriz%d'%i
name= np.zeros((1,5))
for i in range(3):
name2 = 'matriz%d'%i
for j in range(5):
name2[j]=i+j
for i in range(3):
name3 = 'matriz%d'%i
print(name3)
In Python, these 2 lines just assign two different objects to the variable name.
name= 'matriz%d'%i # assign a string
name= np.zeros((1,5)) # assign an array
Some other languages have a mechanism that lets you use the string as variable name, e.g. $name = .... But in Python that is awkward, if not impossible. Instead you should use structures, such as a dictionary.
e.g.
adict = {}
for i in range(3):
name= 'matriz%d'%i
adict[name] = np.zeros((1,5))
You can then access this array via a dictionary reference like: adict['matriz3']
You could also use a list, and access individual arrays by number or list iteration:
alist = [np.zeros((1,5)) for i in range(3)]
for i,A in enumerate(alist): # iteration with index
A[:] = i+np.arange(5)
for a in alist: # simple iteration
print(a)

stop list updating when using del python [duplicate]

This question already has answers here:
error list indices must be integers, not list. Take values of one array use them as indexes to delete values from another array
(3 answers)
Closed 9 years ago.
I have a list where i want to delete certain elements from
I have created a for loop and in this for loop have put del my list[i]
prule is a list of strings containing things like numbers as strings from 0 to 159 its size 11154
def getind(li)
ret = {}
for i, x in enumerate(li):
if x not in ret:
ret[x] = []
ret[x].append(i)
return ret
dups = getind(prule)
for n in dups.get('159',[]):
del rulelines[n]
After a while of doing this list assignment index out of range which I am guessing is because the list gets updated. Is there anything I can use so it doesn't get updated until the for loop is finished
You should browse your list backwards:
for x in range(subjectlength - 1, -1, -1):
del my_list[x]
As I have corrected in my answer here
dups = getind(prules)
indexes = dups.get('156',[])
rulelines = [rulelines[i] for i in range(len(rulelines[:])) if i not in indexes]
Should be what solves your problem.

Categories