【问题标题】:How to find highest values in multiple columns by grouping the row values using python?如何通过使用python对行值进行分组来查找多列中的最大值?
【发布时间】:2017-03-30 23:33:46
【问题描述】:

我正在处理一个包含三列的数据集; roadType(字符串)、汽车和公共汽车(整数值)。

data = [["A", 5, 6], ["B", 7, 3], ["C", 9, 6], ["B", 2, 8], ["A", 4, 8], ["C", 8, 1], ["B", 1, 0]]

现在我想根据第一列中的类型对行数据进行分组,然后从这些组中,我想从两列中找到最高值。 即预期的输出值类似于

output = [["A", 5, 8], ["B", 7, 8], ["C", 9, 6]]

如何使用 python 数据分析库 pandas 或任何其他库?

【问题讨论】:

    标签: python python-2.7 pandas dataframe group-by


    【解决方案1】:

    试试这个代码......请原谅我的语法,我用手机做了这个 XD。

    #pre condition, all integers are greater than zero
    function findMax(tag, list)
        Max1 = 0
        Max2 = 0
    
        for item in list:
            if item[0] == tag:
                if item[1] > Max1:
                    Max1 = item[1]
                if item[2] > Max2:
                    Max2 = item2
        return [tag, Max1, Max2]
    
    
    outputList = [] #your output List
    data = data = [["A", 5, 6], ["B", 7, 3], ["C", 9, 6], ["B", 2, 8], ["A", 4, 8], ["C", 8, 1], ["B", 1, 0]] #your data list
    for item in ["A", "B", "C"...]
         outputList.append( findMax(item, data))
    

    【讨论】:

      【解决方案2】:

      试试这个:

      In [31]: d = pd.DataFrame(data, columns=['roadType','cars','buses'])
      
      In [32]: d
      Out[32]:
        roadType  cars  buses
      0        A     5      6
      1        B     7      3
      2        C     9      6
      3        B     2      8
      4        A     4      8
      5        C     8      1
      6        B     1      0
      
      In [33]: d.groupby('roadType').max().reset_index()
      Out[33]:
        roadType  cars  buses
      0        A     5      8
      1        B     7      8
      2        C     9      6
      

      【讨论】:

      • 我认为这是使用熊猫?
      • @ChrisTomlinson,当然!
      猜你喜欢
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      相关资源
      最近更新 更多