python - 折叠 Python 列表,保留唯一列和最高值

标签 python python-2.7 list pandas

我有一个列表列表

data = [ ['fruit', 'apple', 'v1', 'data 1'],
         ['fruit', 'apple', 'v2', 'data 2'],
         ['fruit', 'apple', 'v3', 'data 3'],
         ['fruit', 'banana', 'v1', 'data 4'],
         ['fruit', 'banana', 'v2', 'data 5'],
         ['animal', 'dog', 'v1', 'data 6'] ]

如何根据前 2 列并使用来自最高 v 的数据进行折叠?

result = [ ['fruit', 'apple', 'v3', 'data 3'],
           ['fruit', 'banana', 'v2', 'data 5'],
           ['animal', 'dog', 'v1', 'data 6'] ]

列表在第一列中排序,但第二列不是。我的解决方案基于假设两列都已排序,因此它不起作用,我不知道从这里去哪里。

previous = []
result = []
for a, b, c, d in data:
    if not all(x in previous for x in [a, b]):
        final.append([a, b, c, d])
        previous = [a, b, c, d]
    else:
        if previous[2] < c:
            final[-1][2] = c
            final[-1][3] = d
            previous = [a, b, c, d]
print result

最佳答案

这是一种方式。

import pandas as pd

data = [ ['fruit', 'apple', 'v1', 'data 1'],
         ['fruit', 'apple', 'v2', 'data 2'],
         ['fruit', 'apple', 'v3', 'data 3'],
         ['fruit', 'banana', 'v1', 'data 4'],
         ['fruit', 'banana', 'v2', 'data 5'],
         ['animal', 'dog', 'v1', 'data 6'] ]

df = pd.DataFrame(data, columns=['Col1', 'Col2', 'Col3', 'Col4'])
df['Grouper'] = df['Col1'] + df['Col2']
df['Order'] = df['Col3'].map(lambda x: int(x[-1]))

df = df.sort_values(['Grouper', 'Order'], ascending=[True, False])\
       .drop_duplicates('Grouper')\
       .drop(['Grouper', 'Order'], 1)

lst = df.values.tolist()

# [['animal', 'dog', 'v1', 'data 6'],
#  ['fruit', 'apple', 'v3', 'data 3'],
#  ['fruit', 'banana', 'v2', 'data 5']]

关于python - 折叠 Python 列表,保留唯一列和最高值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48903434/

相关文章:

python - .strip 不会删除某些字符串上的换行符

python - 找不到 libavformat.so

python - 如何使用 Python 批量插入 Oracle 数据库?

python - 如何在python中获取返回状态

list - 将空列表与 [(a,b)] Haskell 进行比较

python - 将 JSON 行导入 Pandas

javascript - 使用 JavaScript 请求 HTML 页面(Angular 应用程序)

python-2.7 - 了解 Python 中一行中的多个变量赋值

python - 我需要只出现一次的元素数量

python - 更改列表中字典中的键值