本周在一次对话中,我被告知Pandas DataFrames可用于绑定对象属性,但在一个简单的例子中我无法实现:
from pandas import DataFrame
class MyObj:
def __init__(self, x, y):
self.x = x
self.y = y
# create a list of objects
objects = list()
for i in range(1, 5):
objects.append(MyObj(i, i**2))
# create the DataFrame and print it
data = list()
for obj in objects:
data.append([obj.x, obj.y])
df = DataFrame(data=data, columns=['x', 'y'])
print('\nDataFrame content (prev)')
print(df)
# now change the df, and check the objects
df.values[3, 1] = 66
print('\nDataFrame content (post)')
print(df)
print('\nobjects content (post)')
for obj in objects:
print([obj.x, obj.y])
控制台打印输出为:
DataFrame content (prev)
x y
0 1 1
1 2 4
2 3 9
3 4 16
DataFrame content (post)
x y
0 1 1
1 2 4
2 3 9
3 4 66
objects content (post)
[1, 1]
[2, 4]
[3, 9]
[4, 16]
对象内容未被绑定。
是否可以将对象属性绑定到DataFrame?