import pandas as pd
data_dict = {
"key1":1,
"key2":2,
"key3":3
}
# dict转dataframe
data_df = pd.Dataframe.from_dict(data_dict, orient="index").reset_index().rename(columns={"index": "key", 0: "value"})
"""
data_df =
key value
0 key1 1
1 key2 2
2 key3 3
"""
# dataframe转字典
data_dict = data_df.set_index("key")["value"].to_dict()
"""
data_dict = {
"key1":1,
"key2":2,
"key3":3
}
"""
# dataframe按行转字典
data_dict = data_df.to_dict(orient="records")
# 按列转字典
data_dict = data_df.to_dict()
# 列表对象转dataframe,先将列表转成dict,再通过dict转成dataframe
class Person(object):
def __init__(self, name='', year=0, salary=0):
self.name = name
self.year = year
self.salary = salary
def as_dict(self):
return {'name': self.name, 'year': self.year, 'salary': self.salary}
person1 = Person('john', 2017, 100)
person2 = Person('smith', 2016, 200)
person3 = Person('roger', 2016, 500)
person_list = [person1, person2, person3]
df = pd.DataFrame([x.as_dict() for x in person_list])
print(df)
"""
name salary year
0 john 100 2017
1 smith 200 2016
2 roger 500 2016
"""
## 另一种对象列表转dataframe的方式
df = pd.DataFrame([x.__dict__ for x in persion_list])
print(df)
"""
name salary year
0 john 100 2017
1 smith 200 2016
2 roger 500 2016
"""
# dataframe转对象
# 构建对象
class TestObj:
def __init__(self):
self.test_name = None
self.test_id = None
def to_object(self, dict_obj):
if dict_obj is None or len(dict_obj) <= 0:
return None
try:
if isinstance(dict_obj, str):
dict_obj = json.loads(dict_obj)
test_obj = TestObj()
# 保留字段名一致的名字
for k in dict_obj:
if not hasattr(test_obj, k):
continue
setattr(test_obj, k, dict_obj[k])
return test_obj
except Exception as e:
return None
# 构建dataframe
test_df = pd.DataFrame()
test_df["test_name"] = ["xxx", "zzz", "aaa"]
test_df["test_id"] = [1, 2, 3]
# 先转字典列表
test_dic_list = test_df.to_dict(orient="records")
test_obj_list = [TestObj.to_object(x) for x in test_dic_list]
版权声明:本文为weixin_36488653原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。