Python 如何将对象作为值的dict转换为数据帧?

Python 如何将对象作为值的dict转换为数据帧?,python,Python,我有一个Dict,对象作为值,我想从中创建一个DF (忽略南) 可以使用熊猫创建数据帧 将熊猫作为pd导入 dict={'Age':['13','13'],国家['比利时','意大利']} df=pd.数据帧(dict) 字典的键将是列名,值将是行。因此,您将获得: Age Country 0 13 Belgium 1 13 Italy 在尝试下面的代码之前,您应该只在列列表中添加字段,对于这个特定的示例,它们是:名称、年份、国家和奖项。 然后,您可以尝试: df=pd.

我有一个Dict,对象作为值,我想从中创建一个DF (忽略南)


可以使用熊猫创建数据帧

将熊猫作为pd导入
dict={'Age':['13','13'],国家['比利时','意大利']}
df=pd.数据帧(dict)
字典的键将是列名,值将是行。因此,您将获得:

   Age  Country
0  13   Belgium
1  13   Italy

在尝试下面的代码之前,您应该只在列列表中添加字段,对于这个特定的示例,它们是:名称、年份、国家和奖项。 然后,您可以尝试:

df=pd.DataFrame(参与者列表[您的密钥列表中的密钥对密钥],列=列)

对我来说,你想要什么还不是100%清楚。但我假设您想要将
Actor
实例列表转换为数据帧

我们可以将
添加到
Actor
上的\u dict()
方法中,在该方法中,我们将Actor序列化到字典中,并通过简单地使用
pandas.dataframe()
将此类字典的列表转换为数据帧:

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
   Age  Country
0  13   Belgium
1  13   Italy
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