【问题标题】:Using Add() function to merge multiple dataframes in Panda在 Panda 中使用 Add() 函数合并多个数据帧
【发布时间】:2021-05-15 15:31:13
【问题描述】:

给定三个数据框,其中包含一些国家获得的金牌、银牌和铜牌数量,确定每个国家获得的奖牌总数。 注意:所有三个数据框的国家并不完全相同。另外,按照奖牌总数降序对最终数据框进行排序。

这是我下面的代码 - 但我没有得到想要的输出。有人可以提出问题吗?

import numpy as np 
import pandas as pd

# Defining the three dataframes indicating the gold, silver, and bronze medal counts
# of different countries
gold = pd.DataFrame({'Country': ['USA', 'France', 'Russia'],
                         'Medals': [15, 13, 9]}
                    )
silver = pd.DataFrame({'Country': ['USA', 'Germany', 'Russia'],
                        'Medals': [29, 20, 16]}
                    )
bronze = pd.DataFrame({'Country': ['France', 'USA', 'UK'],
                        'Medals': [40, 28, 27]}
                    )
#gold.set_index('Country',inplace = True)
#silver.set_index('Country',inplace = True)
#bronze.set_index('Country',inplace = True)

Total = gold.add(silver,fill_value = 0).add(bronze,fill_value = 0)
Total.sort_values('Medals',ascending = True)

【问题讨论】:

  • 您能否编辑帖子以告诉我们您得到什么输出以及您期望什么输出?

标签: python pandas


【解决方案1】:

你可以试试:

pd.concat([gold, silver, bronze]).groupby('Country').sum().\
          sort_values('Medals', ascending=False).reset_index()

如果您愿意,您可以将三个数据框合二为一。它按国家/地区分组,您将获得每个国家/地区的奖牌总和。最后我们按降序排序并重置索引。

输出:

    Country  Medals
0       USA      72
1    France      53
2        UK      27
3    Russia      25
4   Germany      20

【讨论】:

  • 谢谢队友。两件事-
  • 我原来使用 .add 函数有什么问题?
  • 如果它被分配给一个名为 'Total' 的数据框,你可以添加一个新行: Total['Medals'] = Total['Medals'].astype('float64')
  • @RajibBiswas 整个方法可能不正确。奖牌类型不应从原始数据帧中分离到单独的数据帧中。
  • @TrentonMcKinney,正确的方法应该是什么?
【解决方案2】:

你也可以这样做:

    gold.set_index('Country', inplace=True)
    silver.set_index('Country', inplace=True)
    bronze.set_index('Country', inplace=True)
    #print(gold)
    #print(silver)
    #print(bronze)

   Total= gold.add(silver,    fill_value=0).add(bronze,fill_value=0).sort_values('Medals', ascending=False)

输出:

             Medals
    Country        
    USA        72.0
    France     53.0
    UK         27.0
    Russia     25.0
    Germany    20.0

【讨论】:

    【解决方案3】:
    import numpy as np 
    import pandas as pd
    
    # Defining the three dataframes indicating the gold, silver, and bronze medal counts
    # of different countries
    gold = pd.DataFrame({'Country': ['USA', 'France', 'Russia'],
                             'Medals': [15, 13, 9]}
                        )
    silver = pd.DataFrame({'Country': ['USA', 'Germany', 'Russia'],
                            'Medals': [29, 20, 16]}
                        )
    bronze = pd.DataFrame({'Country': ['France', 'USA', 'UK'],
                            'Medals': [40, 28, 27]}
                        )
    
    # Set the index of the dataframes to 'Country' so that you can get the countrywise
    # medal count
    gold.set_index('Country', inplace = True)
    silver.set_index('Country', inplace = True) 
    bronze.set_index('Country', inplace = True) 
    
    # Add the three dataframes and set the fill_value argument to zero to avoid getting
    # NaN values
    total = gold.add(silver, fill_value = 0).add(bronze, fill_value = 0)
    
    # Sort the resultant dataframe in a descending order
    total = total.sort_values(by = 'Medals', ascending = False).astype("int64")
    
    # Print the sorted dataframe
    print(total)
    
    int64 is used to convert the float value into integer and 64 indicates 64bit memory location
    

    【讨论】:

      【解决方案4】:
      import numpy as np 
      import pandas as pd
      
      # Defining the three dataframes indicating the gold, silver, and bronze medal counts
      # of different countries
      gold = pd.DataFrame({'Country': ['USA', 'France', 'Russia'],
                               'Medals': [15, 13, 9]}
                          )
      silver = pd.DataFrame({'Country': ['USA', 'Germany', 'Russia'],
                              'Medals': [29, 20, 16]}
                          )
      bronze = pd.DataFrame({'Country': ['France', 'USA', 'UK'],
                              'Medals': [40, 28, 27]}
                          )
      gold.set_index('Country' , inplace = True)
      silver.set_index('Country' , inplace = True) 
      bronze.set_index('Country' , inplace = True ) 
      
      total = gold.add(silver , fill_value = 0).add(bronze , fill_value = 0)
      total = total.sort_values(by = 'Medals', ascending = False)
      total = total.astype(int)
      print(total)
      

      【讨论】:

      • 这是您自己的其他答案的副本。请不要发布两次,而是删除一个答案,然后编辑另一个以根据需要进行调整。此外,几句话解释您的代码如何解决问题会很棒!
      猜你喜欢
      • 2017-01-15
      • 1970-01-01
      • 2020-03-03
      • 2017-11-27
      • 2021-08-25
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多