[英]Object representation in Pandas.DataFrame
假設我有以下課程,“MyClass”。
class MyClass:
def __repr__(self):
return 'Myclass()'
def __str__(self):
return 'Meh'
instances = [MyClass() for i in range(5)]
一些實例被創建並存儲在instances
變量中。 現在,我們檢查它的內容。
>>> instances
[Myclass(), Myclass(), Myclass(), Myclass(), Myclass()]
為了表示對象,python 調用__repr__
方法。 但是,當將相同的instances
變量傳遞給pandas.DataFrame
,對象的表示會發生變化並且__str__
方法似乎被調用。
import pandas as pd
df = pd.DataFrame(data=instances)
>>> df
0
0 Meh
1 Meh
2 Meh
3 Meh
4 Meh
為什么對象的表示發生了變化? 我可以確定在 DataFrame 中使用哪種表示嗎?
數據確實存儲為對象。 似乎熊貓在顯示數據幀時只是調用了__str__
方法(隱式)。
您可以通過調用來驗證:
df[0].map(type)
它為列中的每個元素調用type
並返回:
Out[572]:
0 <class '__main__.MyClass'>
1 <class '__main__.MyClass'>
2 <class '__main__.MyClass'>
3 <class '__main__.MyClass'>
4 <class '__main__.MyClass'>
Name: 0, dtype: object
# likewise you get the the
# representation string of the objects
# with:
df[0].map(repr)
Out[578]:
0 Myclass()
1 Myclass()
2 Myclass()
3 Myclass()
4 Myclass()
Name: my_instances, dtype: object
順便說一句,如果要創建一個包含顯式包含數據的列的數據框,請使用:
df = pd.DataFrame({'my_instances': instances})
這樣,您就可以分配一個列名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.