avatar

目录
class_instances_to_dataframe

介绍一下如何把多个class instances 的值存成一个dataframe.

defaultdict

先介绍一个defaultdict.这个是collections的一个骚东西.你建好了以后,每次新建一个Key的时候,value会自动建立一个自定义类型的初始化值.

python
1
import collections

例如 自定义value为list

python
1
list_dict = collections.defaultdict(list)
python
1
list_dict
defaultdict(list, {})
python
1
list_dict["a"].append(1)
python
1
list_dict["b"].append(2)
python
1
list_dict
defaultdict(list, {'a': [1], 'b': [2]})

够骚吧!

多个class instance 转换为defaultdict

python
1
2
3
4
5
class my_class(object):
def __init__(self,a,b,c):
self.a = a
self.b = b
self.c = c
python
1
class1 = my_class(1,2,3)
python
1
class2 = my_class(2,3,4)
python
1
class3 = my_class(3,4,5)

首先把这些classes全部添加到list

python
1
class_list = [class1, class2, class3]

创建一个defaultdict

python
1
class_dict = collections.defaultdict(list)
python
1
2
3
for class_instance in class_list:
for key, value in class_instance.__dict__.items():
class_dict[key].append(value)
python
1
class_dict
defaultdict(list, {'a': [1, 1, 3], 'b': [2, 2, 4], 'c': [3, 3, 5]})

创建dataframe

python
1
import pandas as pd
python
1
frame = pd.DataFrame.from_dict(class_dict)
python
1
frame
a b c
0 1 2 3
1 1 2 3
2 3 4 5

大功告成!!骚吧!!


评论