python - 如何将带有对象的dict作为值转换为数据框?
问题描述
我有一个以对象为值的字典,我想从中创建一个 DF(忽略 Nans)
list_of_actors[key] = value
key -> string
value -> Actor()
class Actor:
def __init__(self,title,link):
self.link = link
self.title = title
self.count = 1
self.yearOfBirth ="NaN"
self.countryOfBirth ="NaN"
self.numberOfAwards = "0"
columns = ['Name', 'Year of birth', 'Country of birth', 'Awards']
Name = self.title
Year of birth = self.yearOfBirth
Country of birth = self.countryOfBirth
Awards = self.numberOfAwards
解决方案
对我来说,不是 100% 清楚你想要什么。但我假设您想将Actor
实例列表转换为数据框。
我们可以在to_dict()
上添加一个方法Actor
,将 Actor 序列化到字典中,然后通过简单地使用将这些字典列表转换为数据框pandas.DataFrame()
:
import pandas as pd
import typing as tp
class Actor:
def __init__(
self,
title: tp.Optional[str] = None,
link: tp.Optional[str] = None,
count: int = 1,
year_of_birth: tp.Optional[int] = None,
country_of_birth: tp.Optional[str] = None,
number_of_awards: int = 0
):
self.link = link
self.title = title
self.count = count
self.yearOfBirth = year_of_birth
self.countryOfBirth = country_of_birth
self.numberOfAwards = number_of_awards
def to_dict(self) -> dict:
return {
"Name": self.title,
"Year of Birth": self.yearOfBirth,
"Country of Birth": self.countryOfBirth,
"Awards": self.numberOfAwards,
}
actors = [Actor() for i in range(10)] # Just to create a list of 10
# actors, put your actual actors
# list here
actor_dicts = [actor.to_dict() for actor in actors]
df = pd.DataFrame(actor_dicts)
>>> df
Name Year of Birth Country of Birth Awards
0 None None None 0
1 None None None 0
2 None None None 0
3 None None None 0
4 None None None 0
5 None None None 0
6 None None None 0
7 None None None 0
8 None None None 0
9 None None None 0
推荐阅读
- javascript - 从字符串解析嵌套的 html 标签时出现问题
- java - 可比 API 文档中的 Java `sgn` 函数
- php - PHP 按 strnatcmp 和另一个特定关键字排序
- csv - 如何对 CSV 文件中的每一行进行一些算术运算
- spring - Spring按需创建Prototype Bean并引用后面创建的bean
- python - 从烧瓶服务发出异步 HTTP 请求
- applescript - 如何使用 Applescript 删除空文件夹?
- perl - 获取 Par::Packer 的所有依赖项?
- java - 创建一个新的数组对象会导致出现几个错误
- progressive-web-apps - 如何在渐进式网络应用程序中进行定期后台同步?