针对强制numpy创建对象数组和numpy强制类型转换这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展C++——动态内存分配2-创建对象数组、Java正确创建对象数组、Numpy不能总是将数
针对强制numpy创建对象数组和numpy强制类型转换这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展C++—— 动态内存分配 2 - 创建对象数组、Java正确创建对象数组、Numpy 不能总是将数组列表转换为数组的对象数组、numpy创建数组元素的获取等相关知识,希望可以帮助到你。
本文目录一览:- 强制numpy创建对象数组(numpy强制类型转换)
- C++—— 动态内存分配 2 - 创建对象数组
- Java正确创建对象数组
- Numpy 不能总是将数组列表转换为数组的对象数组
- numpy创建数组元素的获取
强制numpy创建对象数组(numpy强制类型转换)
我有一个数组:
x = np.array([[1, 2, 3], [4, 5, 6]])
我想创建的另一个数组shape=(1, 1)
和dtype=np.object
其唯一的元素为x。
我已经试过这段代码:
a = np.array([[x]], dtype=np.object)
但是它会产生一系列形状(1, 1, 2, 3)
。
我当然可以做:
a = np.zeros(shape=(1, 1), dtype=np.object)a[0, 0] = x
但我希望该解决方案能够轻松扩展到更大的a
形状,例如:
[[x, x], [x, x]]
无需for
在所有索引上运行循环。
有什么建议可以做到这一点吗?
UPD1
数组可能不同,如:
x = np.array([[1, 2, 3], [4, 5, 6]])y = np.array([[7, 8, 9], [0, 1, 2]])u = np.array([[3, 4, 5], [6, 7, 8]])v = np.array([[9, 0, 1], [2, 3, 4]])[[x, y], [u, v]]
它们也可能具有不同的形状,但是对于那种情况,一个简单的np.array([[x, y], [u, v]])
构造函数就可以了
UPD2
我真的想要一种可以处理任意x, y, u, v
形状(不一定都一样)的解决方案。
答案1
小编典典这是一个非常通用的方法:它适用于嵌套列表,数组列表列表-
不管这些数组的形状是不同还是相等。当数据聚集在一个单独的阵列中时,它也是有效的,这实际上是最棘手的情况。(到目前为止发布的其他方法在这种情况下不起作用。)
让我们从困难的情况开始,一个大数组:
# create example# pick outer shape and inner shape>>> osh, ish = (2, 3), (2, 5)# total shape>>> tsh = (*osh, *ish)# make data>>> data = np.arange(np.prod(tsh)).reshape(tsh)>>># recalculate inner shape to cater for different inner shapes# this will return the consensus bit of all inner shapes>>> ish = np.shape(data)[len(osh):]>>> # block them>>> data_blocked = np.frompyfunc(np.reshape(data, (-1, *ish)).__getitem__, 1, 1)(range(np.prod(osh))).reshape(osh)>>> # admire>>> data_blockedarray([[array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]), array([[10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]), array([[20, 21, 22, 23, 24], [25, 26, 27, 28, 29]])], [array([[30, 31, 32, 33, 34], [35, 36, 37, 38, 39]]), array([[40, 41, 42, 43, 44], [45, 46, 47, 48, 49]]), array([[50, 51, 52, 53, 54], [55, 56, 57, 58, 59]])]], dtype=object)
使用OP的示例,它是数组列表的列表:
>>> x = np.array([[1, 2, 3], [4, 5, 6]])>>> y = np.array([[7, 8, 9], [0, 1, 2]])>>> u = np.array([[3, 4, 5], [6, 7, 8]])>>> v = np.array([[9, 0, 1], [2, 3, 4]])>>> data = [[x, y], [u, v]]>>> >>> osh = (2,2)>>> ish = np.shape(data)[len(osh):]>>> >>> data_blocked = np.frompyfunc(np.reshape(data, (-1, *ish)).__getitem__, 1, 1)(range(np.prod(osh))).reshape(osh)>>> data_blockedarray([[array([[1, 2, 3], [4, 5, 6]]), array([[7, 8, 9], [0, 1, 2]])], [array([[3, 4, 5], [6, 7, 8]]), array([[9, 0, 1], [2, 3, 4]])]], dtype=object)
还有一个具有不同形状子数组的示例(请注意v.T
):
>>> data = [[x, y], [u, v.T]]>>> >>> osh = (2,2)>>> ish = np.shape(data)[len(osh):]>>> data_blocked = np.frompyfunc(np.reshape(data, (-1, *ish)).__getitem__, 1, 1)(range(np.prod(osh))).reshape(osh)>>> data_blockedarray([[array([[1, 2, 3], [4, 5, 6]]), array([[7, 8, 9], [0, 1, 2]])], [array([[3, 4, 5], [6, 7, 8]]), array([[9, 2], [0, 3], [1, 4]])]], dtype=object)
C++—— 动态内存分配 2 - 创建对象数组
// 创建对象数组
#include<iostream>
using namespace std;
class Point
{ public:
Point()
{ X=Y=0; cout<<"Default Constructor called."<<endl; }
Point(int xx,int yy)
{ X=xx; Y=yy; cout<< "Constructor called."<<endl; }
~Point()
{ cout<<"Destructor called."<<endl; }
int GetX() {return X;}
int GetY() {return Y;}
void Move(int x,int y)
{ X=x; Y=y; }
private:
int X,Y;
};
int main()
{
Point *Ptr=new Point[2]; // 创建对象数组
Ptr[0].Move(5,10); // 通过指针访问数组元素的成员
Ptr[1].Move(15,20); // 通过指针访问数组元素的成员
cout<<"Deleting..."<<endl;
delete[ ] Ptr; // 删除整个对象数组
}// 运行结果:
Default Constructor called.
Default Constructor called.
Deleting...
Destructor called.
Destructor called.
// 动态数组类,不需要预先设计好数组的大小
#include<iostream>
using namespace std;
class Point
{ public:
Point()
{ X=Y=0; cout<<"Default Constructor called."<<endl; }
Point(int xx,int yy)
{ X=xx; Y=yy; cout<< "Constructor called."<<endl; }
~Point()
{ cout<<"Destructor called."<<endl; }
int GetX() {return X;}
int GetY() {return Y;}
void Move(int x,int y)
{ X=x; Y=y; }
private:
int X,Y;
};
class ArrayOfPoints
{
public:
ArrayOfPoints(int n)// 根据实际来调整数组大小
{ numberOfPoints=n; points=new Point[n]; }
~ArrayOfPoints()//
{ cout<<"Deleting..."<<endl;
numberOfPoints=0; delete[] points; }
Point& Element(int n)// 返回所需要的元素
{ return points[n]; }
private:
Point *points;
int numberOfPoints;
};
int main()
{
int number;
cout<<"Please enter the number of points:";
cin>>number;
ArrayOfPoints points(number); // 创建对象数组
points.Element(0).Move(5,10); // 通过指针访问数组元素的成员
points.Element(1).Move(15,20); // 通过指针访问数组元素的成员
}
// 运行结果如下:
Please enter the number of points:2
Default Constructor called.
Default Constructor called.
Deleting...
Destructor called.
Destructor called.
Java正确创建对象数组
先从一段简单的错误代码切入,然后在后面提出正确的创建方法。
先考虑这段代码:
public class Student {
private int age;
private String name;
public void Student() {
this.age = 21;
this.name = "someone";
}
public void setAge (int age) {
this.age = age;
}
public int getAge() {
return this.age;
}
}
public class Test {
public static void main(String[] args) {
Student[] students = new Student [3];
students[0].setAge(18);
System.out.println(students[0].getAge());
}
}
运行结果如下,是一个空指针异常:
Exception in thread “main” java.lang.NullPointerException
at Test.main(Test.java:7)
分析原因
Student[] students = new Student [3]; 这一句创建了三个Student的声明,但并没有调用Student的构造方法,等价于,
Student s1;
Student s2;
Student s3;
因此,s1, s2, s3的对象实际上并没有被创建,在内存上也没有一块对应的空间。那么在对象还没有被创建之前,我们自然是不可以调用它的任何方法的。
正确的对象数组创建方法
public class Test {
public static void main(String[] args) {
int i;
Student[] students = new Student [3];
//实例化每一个元素
for (i = 0; i < students.length; i++) {
students[i] = new Student();
}
students[0].setAge(18);
students[1].setAge(30);
students[2].setAge(25);
System.out.println(students[0].getAge());
System.out.println(students[1].getAge());
System.out.println(students[2].getAge());
}
}
Numpy 不能总是将数组列表转换为数组的对象数组
如何解决Numpy 不能总是将数组列表转换为数组的对象数组?
Python 3 版本 3.8.10,numpy 版本 1.19.5
我期待这个代码
import numpy as np
a = np.ones((2,1))
b = np.ones((2,3))
c = [a,b]
print(np.asarray(c,dtype=''object''))
打印与
相同的东西d = np.empty((2,),dtype=''object'')
d[:] = a,b
print(d)
即:
[array([[1.],[1.]]) array([[1.,1.,1.],[1.,1.]])]
.
相反,它引发了一个 ValueError:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/tmp/ipykernel_35004/192805992.py in <module>
3 b = np.ones((2,3))
4 c = [a,b]
----> 5 print(np.asarray(c,dtype=''object''))
~/.local/lib/python3.8/site-packages/numpy/core/_asarray.py in asarray(a,dtype,order)
81
82 """
---> 83 return array(a,copy=False,order=order)
84
85
ValueError: Could not broadcast input array from shape (2,1) into shape (2)
当列表中包含的数组的第一维的长度不同时,不会出现此问题。
这是将数组列表转换为数组对象数组时的问题,其中所有数组的第一维可能相同。
以前,Numpy 会将参差不齐的数组列表转换为参差不齐的对象数组。此行为已被弃用。遗憾的是,将数组指定为“对象”类型的建议修复并不总是有效。
这种转换的当前习语是什么?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
numpy创建数组元素的获取
import numpy as np
arr = np.array(np.arange(12).reshape(3,4))
print(arr)
print(arr[0]) #获取二维数组的第一行
print(arr[1]) #获取二维数组的第二行
print(arr[:3]) #获取二维数组的前三行
print(arr[[0,2]]) #获取二维数组的第1行和第三行
print(arr[:,1]) #获取二维数组的第二列
print(arr[:,-2:]) #获取二维数组的后两列
print(arr[:,[0,2]]) #获取二维数组的第一列和第三列
print(arr[1,3]) #获取二维数组的第二行第四列的元素
今天关于强制numpy创建对象数组和numpy强制类型转换的介绍到此结束,谢谢您的阅读,有关C++—— 动态内存分配 2 - 创建对象数组、Java正确创建对象数组、Numpy 不能总是将数组列表转换为数组的对象数组、numpy创建数组元素的获取等更多相关知识的信息可以在本站进行查询。
本文标签: