python - 根据数量为每个类别选择 1 行

标签 python

我有 5 列的列表,其中第 5 列是数字列表,第 1 列是组标识符。总共有 500 行,但只有 24 组。

我想要的是从每个组标识符中仅选择第 5 列中数字最小的一行。

例如

sheet= """ 
cmn1\tcmn2\tcmn3\tcmn4\tcmn5
rob\t45\tfoo\tbar\t0.0001
Steve\t32\tfoo\tspam\t0.01
rob\t45\tbar\tfoo\t0.0000001
Steve\t32\tfoo\tbar\t0.1"""

这是期望的结果:

cmn1\tcmn2\tcmn3\tcmn4\tcmn5
Steve\t32\tfoo\tspam\t.01
rob\t45\tbar\tfoo\t0.0000001

我在每行列表中都有我的字段,但我不知道如何选择零件[4]中编号最小的行

for line in sheet:
     line = sheet.strip().split("\n")

parts = []

for part in line: 
      parts = []
      parts = part.split("\t")
      print parts [0], parts [1], parts[2], parts[3], parts[4]

最佳答案

sheet= """ cmn1 cmn2 cmn3 cmn4 cmn5
rob  45   foo  bar  0.0001
Steve 32  foo  spam 0.01
rob   45  bar  foo  0.0000001
Steve 32  foo  bar  0.1"""

from collections import defaultdict

d = defaultdict(list)
spl = sheet.splitlines()
header = spl[0]
# iterate over all lines except header
for line in spl[1:]:
    # split once on whitespace using name as the key 
    name = line.split(None,1)[0]
    # append each line to our list of values
    d[name].append(line)

# get min of each line in our values based on the last float value
for v in d.values():
    print(min(v,key=lambda x: float(x.split()[-1])))

Steve 32  foo  spam 0.01
rob   45  bar  foo  0.0000001

如果订单很重要,您可以使用 OrderedDict 广告,并且还会随时检查:

from collections import OrderedDict

d = OrderedDict()
spl = sheet.splitlines()
header = spl[0]
for line in spl[1:]:
    # unpack five elements after splitting
    # using name as key and f to cast to float and compare
    name, _, _, _, f = line.split()
    # if key exists compare float value to current float value
    # keeping or replacing the values based on the outcome
    if name in d and float(d[name].split()[-1]) > float(f):
        d[name] = line
    # else if first time seeing name just add it
    elif name not in d:
        d[name] = line

print(header)
for v in d.values():
    print(v)

cmn1 cmn2 cmn3 cmn4 cmn5
rob   45  bar  foo  0.0000001
Steve 32  foo  spam 0.01

使用您编辑的行,您可以看到输出没有改变,它将与原来完全相同:

for v in d.values():
    print(repr(v))

'rob\t45\tbar\tfoo\t0.0000001'
'Steve\t32\tfoo\tspam\t0.01

关于python - 根据数量为每个类别选择 1 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29017300/

相关文章:

python - 使用 Flask 将 HTML 文本打印为纯文本

python - 解析时出现意外的 EOF

python - 检查矩阵在 Numpy 中是否对称

python - 无法将 cpplist 导入 Cython?

Azure Web 应用服务支持 Python websocket?

python - 处理 IncompleteRead,URLError

Python `yield from` ,还是返回一个生成器?

python - ndarray 到 Structured_array 和 float 到 int

python - 使用自定义 wx.PyGridCellEditor 的 SEGFAULT

python - 如何在pygame中绘制透明线