📌  相关文章
📜  Python – 将列表的字典转换为 Pandas 数据框

📅  最后修改于: 2022-05-13 01:55:29.084000             🧑  作者: Mango

Python – 将列表的字典转换为 Pandas 数据框

在本文中,我们将讨论如何将列表字典转换为 pandas 数据框。

方法一:使用 DataFrame.from_dict()

我们将使用 from_dict 方法。此方法将从类数组或字典的字典构造 DataFrame。

语法

pandas.DataFrame.from_dict(dictionary)

其中字典是输入字典

示例:将学生字典作为输入并显示主题数据然后存储在 pandas 数据框中的程序

Python3
# import pandas module
import pandas as pd
  
  
# create a dictionary for three subjects with list
# of three subjects for each student
data = {
    'manoj': ["java", "php", "python"],
    'tripura': ["bigdata", "c/cpp", "R"],
    'uma': ["js/css/html", "ruby", "IOT"]
}
  
# convert to dataframe using from_dict method
pd.DataFrame.from_dict(data)


Python3
# import pandas module
import pandas as pd
  
  
# create a dictionary for three subjects with list
# of three subjects for each student
data = {
    'manoj': ["java", "php", "python"],
    'tripura': ["bigdata", "c/cpp", "R"],
    'uma': ["js/css/html", "ruby", "IOT"]
}
  
# convert to dataframe using from_dict method
# with orient
pd.DataFrame.from_dict(data, orient='index')


Python3
# import pandas module
import pandas as pd
  
# create a dictionary for three subjects with list
# of three subjects for each student
data = {
    'manoj': ["java", "php", "python"],
    'tripura': ["bigdata", "c/cpp", "R"],
    'uma': ["js/css/html", "ruby", "IOT"]
}
  
# convert to dataframe using series with items() method
pd.DataFrame({key: pd.Series(val) for key, val in data.items()})


输出

假设如果我们想获取带有键作为行名的数据框,那么我们必须使用 orient 参数

语法

pd.DataFrame.from_dict(data,orient='index')

例子:

Python3

# import pandas module
import pandas as pd
  
  
# create a dictionary for three subjects with list
# of three subjects for each student
data = {
    'manoj': ["java", "php", "python"],
    'tripura': ["bigdata", "c/cpp", "R"],
    'uma': ["js/css/html", "ruby", "IOT"]
}
  
# convert to dataframe using from_dict method
# with orient
pd.DataFrame.from_dict(data, orient='index')

输出

方法 2:使用 pd.Series()

在这里,我们通过使用 items() 方法在 dataframe 方法中使用 Series 数据结构

句法:

pd.DataFrame({ key: pd.Series(val) for key, val in dictionary.items() })

在哪里

  • dictionary.items() 是从字典中获取项目的方法
  • pd.Series(val) 将从 items() 方法中获取一系列值

例子:

Python3

# import pandas module
import pandas as pd
  
# create a dictionary for three subjects with list
# of three subjects for each student
data = {
    'manoj': ["java", "php", "python"],
    'tripura': ["bigdata", "c/cpp", "R"],
    'uma': ["js/css/html", "ruby", "IOT"]
}
  
# convert to dataframe using series with items() method
pd.DataFrame({key: pd.Series(val) for key, val in data.items()})

输出