Pandas - 使用索引中的成对组合将数据帧转换为方阵

evo*_*olk 5 python optimization pandas

我正在将数据框转换为方阵。数据框有一个索引,并且只有一列带有浮点数。我需要做的是计算所有索引对,并为每对取两个关联列值的平均值。因此,通常的主元函数只是解决方案的一部分。

目前,该函数的估计复杂度为 O(n^2),这并不好,因为我必须处理一次包含数百行数据帧的较大输入。我可以采取另一种更快的方法吗?

输入示例(为简单起见,此处使用整数):

df = pd.DataFrame([3, 4, 5])
Run Code Online (Sandbox Code Playgroud)

更新:转换逻辑

对于示例中的输入数据框:

   0

0  3
1  4
2  5
Run Code Online (Sandbox Code Playgroud)

我执行以下操作(但并不声称这是最好的方法):

  • 获取所有索引对:(0,1), (1,2), (0,2)
  • 对于每一对,计算其值的平均值:(0,1):3.5、(1,2):4.5、(0,2):4.0
  • 使用每对中的索引作为列和行标识符以及对角线上的零来构建对称方阵(如所需输出所示)。

代码位于turn_table_into_square_matrix()中。

期望的输出:

    0   1   2

0   0.0 3.5 4.0
1   3.5 0.0 4.5
2   4.0 4.5 0.0
Run Code Online (Sandbox Code Playgroud)

目前的实施:

import pandas as pd
from itertools import combinations 
import time
import string
import random


def turn_table_into_square_matrix(original_dataframe):

    # get all pairs of indices 
    index_pairs = list(combinations(list(original_dataframe.index),2))

    rows_for_final_dataframe = []

    # collect new data frame row by row - the time consuming part
    for pair in index_pairs:
        subset_original_dataframe = original_dataframe[original_dataframe.index.isin(list(pair))]
        rows_for_final_dataframe.append([pair[0], pair[1], subset_original_dataframe[0].mean()])
        rows_for_final_dataframe.append([pair[1], pair[0], subset_original_dataframe[0].mean()])

    final_dataframe = pd.DataFrame(rows_for_final_dataframe)

    final_dataframe.columns = ["from", "to", "weight"]
    final_dataframe_pivot = final_dataframe.pivot(index="from", columns="to", values="weight")
    final_dataframe_pivot = final_dataframe_pivot.fillna(0)

    return final_dataframe_pivot
Run Code Online (Sandbox Code Playgroud)

计时性能的代码:

for size in range(50, 600, 100):

    index = range(size)
    values = random.sample(range(0, 1000), size)
    example = pd.DataFrame(values, index)

    print ("dataframe size", example.shape)

    start_time = time.time()
    turn_table_into_square_matrix(example)
    print ("conversion time:", time.time()-start_time)
Run Code Online (Sandbox Code Playgroud)

计时结果:

dataframe size (50, 1)
conversion time: 0.5455281734466553

dataframe size (150, 1)
conversion time: 5.001590013504028

dataframe size (250, 1)
conversion time: 14.562285900115967

dataframe size (350, 1)
conversion time: 31.168692111968994

dataframe size (450, 1)
conversion time: 49.07127499580383

dataframe size (550, 1)
conversion time: 78.73740792274475
Run Code Online (Sandbox Code Playgroud)

因此,50 行的数据帧只需半秒即可转换,而 550 行(长 11 倍)的数据帧则需要 79 秒(长 11^2 倍以上)。有没有更快的方法来解决这个问题?

tgy*_*tgy 4

我认为不可能有比O(n^2)该计算更好的方法了。正如 @piiipmatz 所建议的,您应该尝试使用 numpy 执行所有操作,然后将结果放入pd.DataFrame. 您的问题听起来像是numpy.add.at.

这是一个简单的例子

import numpy as np
import itertools

# your original array
x = np.array([1, 4, 8, 99, 77, 23, 4, 45])
n = len(x)
# all pairs of indices in x
a, b = zip(*list(itertools.product(range(n), range(n))))
a, b = np.array(a), np.array(b)
# resulting matrix
result = np.zeros(shape=(n, n))

np.add.at(result, [a, b], (x[a] + x[b]) / 2.0)

print(result)
# [[  1.    2.5   4.5  50.   39.   12.    2.5  23. ]
# [  2.5   4.    6.   51.5  40.5  13.5   4.   24.5]
# [  4.5   6.    8.   53.5  42.5  15.5   6.   26.5]
# [ 50.   51.5  53.5  99.   88.   61.   51.5  72. ]
# [ 39.   40.5  42.5  88.   77.   50.   40.5  61. ]
# [ 12.   13.5  15.5  61.   50.   23.   13.5  34. ]
# [  2.5   4.    6.   51.5  40.5  13.5   4.   24.5]
# [ 23.   24.5  26.5  72.   61.   34.   24.5  45. ]]
Run Code Online (Sandbox Code Playgroud)