📜  从字典列表创建 Pandas DataFrame

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

从字典列表创建 Pandas DataFrame

Pandas DataFrame 是一种二维标记数据结构,具有可能不同类型的列。它通常是最常用的 pandas 对象。

Pandas DataFrame 可以通过多种方式创建。让我们讨论如何从字典列表创建 Pandas DataFrame。

代码#1:

# Python code demonstrate how to create  
# Pandas DataFrame by lists of dicts. 
import pandas as pd 
    
# Initialise data to lists. 
data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'},
        {'Geeks':10, 'For': 20, 'geeks': 30}] 
    
# Creates DataFrame. 
df = pd.DataFrame(data) 
    
# Print the data 
df 

输出:

代码#2:index

# Python code demonstrate how to create  
# Pandas DataFrame by lists of dicts. 
import pandas as pd 
    
# Initialise data to lists. 
data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'},
        {'Geeks':10, 'For': 20, 'geeks': 30}] 
    
# Creates DataFrame. 
df = pd.DataFrame(data, index =['ind1', 'ind2']) 
    
# Print the data 
df 

输出:

代码 #3:使用indexcolumns

# Python code demonstrate how to create  
# Pandas DataFrame by lists of dicts. 
import pandas as pd 
    
# Initialise data to lists. 
data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'},
        {'Geeks':10, 'For': 20, 'geeks': 30}] 
    
# With two column indices, values same  
# as dictionary keys 
df1 = pd.DataFrame(data, index =['ind1', 'ind2'],
                      columns =['Geeks', 'For']) 
     
# With two column indices with  
# one index with other name 
df2 = pd.DataFrame(data, index =['indx', 'indy']) 
     
# print for first data frame 
print (df1, "\n") 
     
# Print for second DataFrame. 
print (df2) 

输出: