将 n*3 矩阵转置为 n*m 矩阵

时间:2021-01-07 03:00:34

标签: python python-3.x

对于网络服务器,我试图生成一个报告,给出在某个固定持续时间(比如一个小时)内具有各种响应代码的请求数量。

从原始 http 访问日志数据中,我首先生成了一个数组数组,其中每行有 3 个单元格:小时、响应代码和请求数。然后我生成最终结果。逻辑很简单,对于输入中的每一行,

我有它的工作,看到小样本,但它似乎不是“pythonic”我想知道是否有更好的方法来做到这一点。我有 Python 初学者技能,没有接触过各种数据处理库。

有没有更好的方法来做到这一点?有没有可以直接从初始原始数据生成最终结果的库?

另外,我很确定转置不是这种转换的正确名称,如果有人也可以纠正我,不胜感激。

#! /usr/bin/python3

'''
data is an array of array n*3:
h  resp  count
1   200     15
1   201     23
2   200      9
2   201     75
2   404      5

result is an array of n*m:
   200  202   404
1   15   23     0
2    9   75     5
'''

def process(data):
  result = [[None]]
  for inrow in data:
    r,c,v = inrow[0], inrow[1], inrow[2]
    row = find_row(result, r)
    idx = find_column_index(result, c)
    row[idx] = v
  return result

def find_row(result, r):
  row = next((row for row in result[1:] if row[0] == r), None)
  if not row:
    row = [r]
    result.append(row)
    for x in result[0][1:]:
      row.append(0)
  return row

def find_column_index(result, c):
  columns = result[0]
  idx = next((idx for idx in range(len(columns)) if columns[idx] == c), None)
  if not idx:
    columns.append(c)
    for row in result[1:]:
      row.append(0)
    idx = len(columns) - 1
  return idx

def test():
  #import pdb; pdb.set_trace()
  arr = [
    [1, "200", 15],
    [1, "202", 23],
    [2, "200", 9],
    [2, "202", 75],
    [2, "404", 5]
    ]
  result = process(arr)
  print(result)

if __name__ == "__main__":
  test()

1 个答案:

答案 0 :(得分:1)

Pandas 可以为您轻松解决这个问题,只需将数据帧传输到数据透视表:

import pandas as pd
df = pd.DataFrame(arr = [
    [1, "200", 15],
    [1, "202", 23],
    [2, "200", 9],
    [2, "202", 75],
    [2, "404", 5]
    ],columns = ['h', 'resp', 'count'])
pivot = df.pivot(values='count',index='h',columns='resp')
print(pivot)