首页 > 解决方案 > 如何将带有对象的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

标签: python

解决方案


对我来说,不是 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

推荐阅读