📜  Python|从等长列表的字典创建 Pandas 数据框

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

Python|从等长列表的字典创建 Pandas 数据框

给定一个等长列表的字典,任务是从中创建一个 Pandas DataFrame。

在 Pandas 中有多种创建 DataFrame 的方法。一种方法是将包含等长列表的字典转换为值。让我们通过示例讨论如何从等长列表的字典创建 Pandas 数据框。

示例#1:给定一个字典,其中包含板球格式作为和前五支球队的列表作为

# Import pandas package 
import pandas as pd
  
# Define a dictionary containing ICC rankings
rankings = {'test': ['India', 'South Africa', 'England',
                            'New Zealand', 'Australia'],
              'odi': ['England', 'India', 'New Zealand',
                            'South Africa', 'Pakistan'],
               't20': ['Pakistan', 'India', 'Australia', 
                              'England', 'New Zealand']}
  
# Convert the dictionary into DataFrame
rankings_pd = pd.DataFrame(rankings)
  
# Increment the index so that index 
# starts at 1 (starts at 0 by default) 
rankings_pd.index += 1
  
rankings_pd

输出:


示例 #2:给定三个列表test_batsmenodi_batsment20_batsmen 。所以我们首先需要把这个数据转换成字典,然后再把字典转换成DataFrame。

# Import pandas package 
import pandas as pd
  
# Lists of top 5 batsmen for each format
test_batsmen = ['Virat Kohli', 'Steve Smith', 'Kane Williamson',
                                     'Joe Root', 'David Warner']
odi_batsmen = ['Virat Kohli', 'Rohit Sharma', 'Joe Root',
                            'David Warner', 'Babar Azam']
t20_batsmen = ['Babar Azam', 'Aaron Finch', 'Colin Munro',
                           'Lokesh Rahul', 'Fakhar Zaman']
  
# Define a dictionary containing ICC rankings for batsmen
rankings_batsmen = {'test': test_batsmen,
                      'odi': odi_batsmen,
                      't20': t20_batsmen}
  
# Convert the dictionary into DataFrame
rankings_batsmen_pd = pd.DataFrame(rankings_batsmen)
  
# Increment the index so that index
# starts at 1 (starts at 0 by default) 
rankings_batsmen_pd.index += 1
  
rankings_batsmen_pd

输出: