简体   繁体   English

如何为numpy数组变量中的每一行制作不同的元素?

[英]How to make different element for each row in numpy array variable?

I try to make the output y that have different element per row.我尝试使输出 y 每行具有不同的元素。 But when I print y again, the output show that y have the same element for each row.但是当我再次打印 y 时,输出显示 y 对于每一行都有相同的元素。 What is the correct way to create y with different element for each row?为每行创建具有不同元素的 y 的正确方法是什么?

import numpy as np
class temp:
  x = []
y = np.tile(temp, (3, 1))
y

Output输出

for i in range(3):
  y[i, 0].x = np.random.rand(1,5)
  print(y[i,0].x)

Output输出

for i in range(3):
  print(y[i,0].x)

Output输出

You shouldn't be trying to make arrays of custom class objects.您不应该尝试制作自定义类对象的数组。 This will not replicate the MATLAB struc (in your next question).这不会复制 MATLAB struc (在您的下一个问题中)。

But if you do define a class, use a more conventional format, such as:但如果你确实定义了一个类,请使用更传统的格式,例如:

In [39]: class Temp:
    ...:     def __init__(self, x):
    ...:         self.x = x
    ...:     def __repr__(self):
    ...:         return f'Temp ({self.x})'
    ...:         

In [40]: a = Temp([1,2,3]); b = Temp([4,5])

In [41]: a
Out[41]: Temp ([1, 2, 3])

In [42]: a.x
Out[42]: [1, 2, 3]

In [43]: b
Out[43]: Temp ([4, 5])

a and b are instances of the class, each with their own x attribute. ab是类的实例,每个都有自己的x属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 测试numpy数组中的行是否与给定行相同或每个元素不同 - Testing if rows in a numpy array are the same as a given row or different by each element 如何将 numpy 数组的每一行向量与其自身和每个元素进行比较 - How to compare each row of vectors of numpy array to itself and every element 如何为 numpy 数组中的每一行使用不同的索引? - How do I use a different index for each row in a numpy array? 如何每次更改 2d numpy 数组的不同元素 - how to change a different element of a 2d numpy array each time 如何基于为每个元素调用的函数制作numpy数组? - How to make numpy array based on function called for each element? 更新 numpy 数组中每一行的最后一个元素 - Update last element of each row in numpy array numpy 数组索引:每行不同的列 - numpy array indexing: different columns of each row 如何使 numpy 数组中的一个元素与另一个 numpy 数组中的另一个元素共享相同的 memory 地址? - How to make one element in a numpy array share the same memory address with another element in a different numpy array? 将一个数组的每一行与numpy中另一个数组的每个元素相乘 - Multiply each row of one array with each element of another array in numpy 使numpy 2d数组中每行中除最大n元素之外的所有元素为零 - Make all the elemant zero except max n element in each row in numpy 2d-array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM