Pandas 未正确显示系列中的值

Pandas Not Displaying Value Correctly in Series

我有一个名为 Point() 的 class,我希望打印出来的是 WKT,而不是从服务中得到的 JSON。

Point class 继承自 dict,class 上的所有内容都很好用,除非我在 ipython 中显示列或打印 dataframe 对象。

我在点 class 上尝试了以下方法(简化 class):

class Point(dict):
    def __init__(self, iterable):
       self._coords = iterable
    def __str__(self):
       return 'Point(%s,%s)' % (self._coords['x'], self._coords['y'])
    def __repr__(self):
       return 'Point(%s,%s)' % (self.x, self.y)
    def _repr_html_(self):
       return self.__str__()
    def _repr_pretty_(self):
       return self.__str__()

示例:

>>> pt = Point({"x" : -118.15, "y" : 33.80, "spatialReference" : {"wkid" : 4326}})
>>> df = pd.DataFrame(data=[['A', pt]], columns=['foo', 'SHAPE'])
>>> df.SHAPE
  foo                                              SHAPE
0   A  {'x': -118.15, 'y': 33.8, 'spatialReference': ...

但如果我这样做

>>> df.SHAPE[0]
"POINT (-118.15000000000001 33.799999999999997)"

哪个是正确的期望输出。

如何让 DataFrame 支持我的 classes reprstr?

这里是另一个编辑来显示我看到的非常基本的问题:

class foo(dict):
    def __init__(self, iterable=None, **kwargs):
        if iterable is None:
            iterable = ()
        super(foo, self).__init__(iterable)
        self.update(kwargs)
    def __repr__(self):
        return ",".join(self.keys())
    def __str__(self):
        return ",".join(self.keys())

f = foo({'alpha' : 'b',
    'beta' : 'c'})

import pandas as pd
pd.DataFrame(data=[['A', 1, f]], columns=['D', 'F', 'G'])

系列 'G' 的输出不符合 classes __repr____str__.

谢谢

您在这里覆盖的是 object 在 python 中的内置函数。 pandas对此一无所知。

正确的是,当您尝试访问 repl 中 G 中的项目时,您会得到正确的覆盖输出,因为这是您在对象级别指定的内容。但是当您尝试打印 G 本身时,您将得到对象表示而不是 str(object)repr(object)。你可以阅读更多 here

repr(对象)

Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

简而言之,重写__repr__操作的是repr()returns,它是而不是操作对象表示。

G列中的

foo仍然是对象,不是str(foo)

因此你需要给 G str(object)repr(object) 作为它的项目。 您在这里假设当您将对象提供给 DataFrame 时,pandas 会自动将对象表示转换为 str(object)repr(object)。不是这种情况。

初次尝试达到您想要的结果,您可以这样做:

import pandas as pd
df = pd.DataFrame(data=[['A', 1, str(f)]], columns=['D', 'F', 'G'])
print(df)

# output
  D F           G
0 A 1 alpha, beta

我不得不转到 github 页面以获得 Pandas,并从开发团队那里发现他们使用的 pprint 函数不支持 __str____repr__ 在可迭代对象上。因此,如果您从 dict 继承,您将从字典中获取默认打印。基本的解决方案是不继承 dict 而只使用默认对象。