我知道继承是not the simplest alternative在使用 pandas 时,但我很好奇如何获得我想要的结果。
假设我有一个函数,它从一个字符串返回一个字典(该字符串可以是一个路径,一个集合的名称...):
def str_to_dict(string):
...
dic = str_to_dict(s1)
dic
>>> {'col_1' : ['a','b',...], 'col2': [1, 2, ...]
我想做的是创建一个 pandas.DataFrame 的子类,它包含 dic 的数据,同时使用上面的方法通过字符串初始化 并将字符串保留为属性。
我知道简单地将字典传递给 pandas.DataFrame 会在某些情况下起作用,但我可能需要更改方向(键是索引而不是列名),所以我想使用 from_dict 构造函数来获取我的 DataFrame。
这是我的工作:
# Works but only if you want the keys of the dictionary to be the columns
class MySubClass(pandas.DataFrame):
def __init__(self, string):
self.my_string_attribute = string
dic = str_to_dict(string)
pandas.DataFrame.__init__(dic)
# Does not work, throws a RecursionError
# It is because __init__ is used with the from_dict constructor and calls itself
class MySubClass(pandas.DataFrame):
def __init__(self, string):
self.my_string_attribute = string
self.from_dict(str_to_dict(string)) # Here I could add any option needed
再一次,我知道继承还有其他选择,我可能会使用组合来继续我的项目,但我只是好奇如何才能让它发挥作用
请您参考如下方法:
此处详细说明了您尝试执行的操作不起作用的原因:
https://github.com/pandas-dev/pandas/issues/2859
And this won't work because it does not return an instance of your subclass. (Bunch of issues here):
# Works but only if you want the keys of the dictionary to be the columns class MySubClass(pandas.DataFrame): def __init__(self, string): self.my_string_attribute = string dic = str_to_dict(string) pandas.DataFrame.__init__(dic)
所以您可以像这样向 pd.DataFrame 类添加功能:
import ast
def str_to_dict(string):
return ast.literal_eval(string)
class MySubClass(pd.DataFrame):
def from_str(self, string):
df_obj = super().from_dict(str_to_dict(string))
df_obj.my_string_attribute = string
return df_obj
data = "{'col_1' : ['a','b'], 'col2': [1, 2]}"
obj = MySubClass().from_str(data)
type(obj)
# __main__.MySubClass
obj.my_string_attribute
# "{'col_1' : ['a','b'], 'col2': [1, 2]}"
