Dem*_*unt 9 python numpy pandas
我可以像在列表中那样"存储"pandas/numpy Series-DataFrame/ndarray中的类实例吗?或者这些库支持内置类型(数字,字符串).
例如,我有Point带x,y坐标,我想存储Points的Plane,这将返回Point与给定的坐标.
#my class
class MyPoint:
def __init__(self, x,y):
self.x = x
self.y = y
@property
def x(self):
return self.x
@property
def y(self):
return self.y
Run Code Online (Sandbox Code Playgroud)
在这里我创建实例:
first_point = MyClass(1,1)
second_point = MyClass(2,2)
Run Code Online (Sandbox Code Playgroud)
我可以将实例存储在某个列表中
my_list = []
my_list.append(first_point)
my_list.append(second_point)
Run Code Online (Sandbox Code Playgroud)
列表中的问题是它的索引与x,y属性不对应.
字典/ DataFrame方法:
Plane = {"x" : [first_point.x, second_point.x], "y" : [first_point.y, second_point.y], "some_reference/id_to_point_instance" = ???}
Plane_pd = pd.DataFrame(Plane)
Run Code Online (Sandbox Code Playgroud)
我读过帖子,使用实例的"id"作为DataFrame中的第三列值可能会导致垃圾收集器出现问题.
Ste*_*uch 11
A pandas.DataFrame会很乐意存储python对象.
一些测试代码来演示......
class MyPoint:
def __init__(self, x, y):
self._x = x
self._y = y
@property
def x(self):
return self._x
@property
def y(self):
return self._y
my_list = [MyPoint(1, 1), MyPoint(2, 2)]
print(my_list)
plane_pd = pd.DataFrame([[p.x, p.y, p] for p in my_list],
columns=list('XYO'))
print(plane_pd.dtypes)
print(plane_pd)
Run Code Online (Sandbox Code Playgroud)
[<__main__.MyPoint object at 0x033D2AF0>, <__main__.MyPoint object at 0x033D2B10>]
X int64
Y int64
O object
dtype: object
X Y O
0 1 1 <__main__.MyPoint object at 0x033D2AF0>
1 2 2 <__main__.MyPoint object at 0x033D2B10>
Run Code Online (Sandbox Code Playgroud)
请注意,列表中的两个对象是数据框中的两个对象.另请注意O列的dtype 是object.
| 归档时间: |
|
| 查看次数: |
5895 次 |
| 最近记录: |