两个DataFrame(Python / Pandas)中每行和每列之间的差异

时间:2014-08-31 21:33:51

标签: python pandas

是否有更有效的方法将一个DF中每一行的每列与另一个DF的每一行中的每一列进行比较?这对我来说很邋,,但我的循环/应用尝试要慢得多。

df1 = pd.DataFrame({'a': np.random.randn(1000),
                   'b': [1, 2] * 500,
                   'c': np.random.randn(1000)},
                   index=pd.date_range('1/1/2000', periods=1000))
df2 = pd.DataFrame({'a': np.random.randn(100),
                'b': [2, 1] * 50,
                'c': np.random.randn(100)},
               index=pd.date_range('1/1/2000', periods=100))
df1 = df1.reset_index()
df1['embarrassingHackInd'] = 0
df1.set_index('embarrassingHackInd', inplace=True)
df1.rename(columns={'index':'origIndex'}, inplace=True)
df1['df1Date'] = df1.origIndex.astype(np.int64) // 10**9
df1['df2Date'] = 0
df2 = df2.reset_index()
df2['embarrassingHackInd'] = 0
df2.set_index('embarrassingHackInd', inplace=True)
df2.rename(columns={'index':'origIndex'}, inplace=True)
df2['df2Date'] = df2.origIndex.astype(np.int64) // 10**9
df2['df1Date'] = 0
timeit df3 = abs(df1-df2)

10个循环,最佳3:每循环60.6毫秒

我需要知道进行了哪个比较,因此每个对立指数的丑陋添加到比较DF,以便最终在最终的DF中。

提前感谢您的任何帮助。

1 个答案:

答案 0 :(得分:6)

您发布的代码显示了一种生成减法表的巧妙方法。然而,它并没有发挥熊猫的优势。 Pandas DataFrames将基础数据存储在基于列的块中。因此,按列完成数据检索的速度最快,而不是按行完成。由于所有行都具有相同的索引,因此通过行执行减法(将每行与每隔一行配对),这意味着在df1-df2中进行了大量基于行的数据检索。这对于Pandas来说并不理想,特别是当并非所有列都具有相同的dtype时。

减法表是NumPy擅长的:

In [5]: x = np.arange(10)

In [6]: y = np.arange(5)

In [7]: x[:, np.newaxis] - y
Out[7]: 
array([[ 0, -1, -2, -3, -4],
       [ 1,  0, -1, -2, -3],
       [ 2,  1,  0, -1, -2],
       [ 3,  2,  1,  0, -1],
       [ 4,  3,  2,  1,  0],
       [ 5,  4,  3,  2,  1],
       [ 6,  5,  4,  3,  2],
       [ 7,  6,  5,  4,  3],
       [ 8,  7,  6,  5,  4],
       [ 9,  8,  7,  6,  5]])

您可以将x视为df1的一列,将y视为df2的一列。您将在下面看到,NumPy可以使用基本相同的语法以基本相同的方式处理df1的所有列和df2的所有列。


以下代码定义了origusing_numpyorig是您发布的代码,using_numpy是使用NumPy数组执行减法的替代方法:

In [2]: %timeit orig(df1.copy(), df2.copy())
10 loops, best of 3: 96.1 ms per loop

In [3]: %timeit using_numpy(df1.copy(), df2.copy())
10 loops, best of 3: 19.9 ms per loop

import numpy as np
import pandas as pd
N = 100
df1 = pd.DataFrame({'a': np.random.randn(10*N),
                   'b': [1, 2] * 5*N,
                   'c': np.random.randn(10*N)},
                   index=pd.date_range('1/1/2000', periods=10*N))
df2 = pd.DataFrame({'a': np.random.randn(N),
                'b': [2, 1] * (N//2),
                'c': np.random.randn(N)},
               index=pd.date_range('1/1/2000', periods=N))

def orig(df1, df2):
    df1 = df1.reset_index() # 312 µs per loop
    df1['embarrassingHackInd'] = 0 # 75.2 µs per loop
    df1.set_index('embarrassingHackInd', inplace=True) # 526 µs per loop
    df1.rename(columns={'index':'origIndex'}, inplace=True) # 209 µs per loop
    df1['df1Date'] = df1.origIndex.astype(np.int64) // 10**9 # 23.1 µs per loop
    df1['df2Date'] = 0

    df2 = df2.reset_index()
    df2['embarrassingHackInd'] = 0
    df2.set_index('embarrassingHackInd', inplace=True)
    df2.rename(columns={'index':'origIndex'}, inplace=True)
    df2['df2Date'] = df2.origIndex.astype(np.int64) // 10**9
    df2['df1Date'] = 0
    df3 = abs(df1-df2) # 88.7 ms per loop  <-- this is the bottleneck
    return df3

def using_numpy(df1, df2):
    df1.index.name = 'origIndex'
    df2.index.name = 'origIndex'
    df1.reset_index(inplace=True) 
    df2.reset_index(inplace=True) 
    df1_date = df1['origIndex']
    df2_date = df2['origIndex']
    df1['origIndex'] = df1_date.astype(np.int64) 
    df2['origIndex'] = df2_date.astype(np.int64) 

    arr1 = df1.values
    arr2 = df2.values
    arr3 = np.abs(arr1[:,np.newaxis,:]-arr2) # 3.32 ms per loop vs 88.7 ms 
    arr3 = arr3.reshape(-1, 4)
    index = pd.MultiIndex.from_product(
        [df1_date, df2_date], names=['df1Date', 'df2Date'])
    result = pd.DataFrame(arr3, index=index, columns=df1.columns)
    # You could stop here, but the rest makes the result more similar to orig
    result.reset_index(inplace=True, drop=False)
    result['df1Date'] = result['df1Date'].astype(np.int64) // 10**9
    result['df2Date'] = result['df2Date'].astype(np.int64) // 10**9
    return result

def is_equal(expected, result):
    expected.reset_index(inplace=True, drop=True)
    result.reset_index(inplace=True, drop=True)

    # expected has dtypes 'O', while result has some float and int dtypes. 
    # Make all the dtypes float for a quick and dirty comparison check
    expected = expected.astype('float')
    result = result.astype('float')
    columns = ['a','b','c','origIndex','df1Date','df2Date']
    return expected[columns].equals(result[columns])

expected = orig(df1.copy(), df2.copy())
result = using_numpy(df1.copy(), df2.copy())
assert is_equal(expected, result)

x[:, np.newaxis] - y工作原理:

此表达式利用了NumPy广播。 要了解广播 - 通常是NumPy - 了解阵列的形状是值得的:

In [6]: x.shape
Out[6]: (10,)

In [7]: x[:, np.newaxis].shape
Out[7]: (10, 1)

In [8]: y.shape
Out[8]: (5,)

[:, np.newaxis]右侧上向x添加新轴,因此形状为(10, 1)。因此,x[:, np.newaxis] - y是形状(10, 1)的数组的减法,其形状为(5,)

从表面上看,这没有意义,但是NumPy数组广播它们的形状according to certain rules,试图使它们的形状兼容。

第一条规则是可以在左侧上添加新轴。因此,形状(5,)的数组可以广播自己以塑造(1, 5)

下一条规则是长度为1的轴可以将自身广播为任意长度。数组中的值只需根据需要在额外维度上重复。

因此,当形状(10, 1)(1, 5)的数组在NumPy算术运算中放在一起时,它们都被广播到形状为(10, 5)的数组:

In [14]: broadcasted_x, broadcasted_y = np.broadcast_arrays(x[:, np.newaxis], y)

In [15]: broadcasted_x
Out[15]: 
array([[0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4],
       [5, 5, 5, 5, 5],
       [6, 6, 6, 6, 6],
       [7, 7, 7, 7, 7],
       [8, 8, 8, 8, 8],
       [9, 9, 9, 9, 9]])

In [16]: broadcasted_y
Out[16]: 
array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4]])

因此x[:, np.newaxis] - y相当于broadcasted_x - broadcasted_y

现在,有了这个简单的例子,我们可以看看 arr1[:,np.newaxis,:]-arr2

arr1的形状为(1000, 4)arr2的形状为(100, 4)。我们想要减去长度为4的轴,沿着1000长度轴的每一行,以及沿着100长度轴的每一行。换句话说,我们希望减法形成一个形状(1000, 100, 4)的数组。

重要的是,我们不希望1000-axis100-axis进行互动。 我们希望它们位于不同的轴

因此,如果我们将arr1这样的轴添加到arr1[:,np.newaxis,:],那么它的形状将变为

In [22]: arr1[:, np.newaxis, :].shape
Out[22]: (1000, 1, 4)

而现在,NumPy广播将两个阵列都推到了(1000, 100, 4)的常见形状。 Voila,一个减法表。

要将值按到形状(1000*100, 4)的2D数据框中,我们可以使用reshape

arr3 = arr3.reshape(-1, 4)

-1告诉NumPy用重新整形所需的正整数替换-1。由于arr的值为1000 * 100 * 4,因此-1将替换为1000*100。使用-1比编写1000*100更好,因为即使我们更改了df1df2中的行数,它也允许代码正常工作。