是否有更有效的方法将一个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)
Run Code Online (Sandbox Code Playgroud)
10个循环,最佳3:60.6 ms每个循环
我需要知道进行了哪种比较,因此将每个相反指数的丑陋添加到比较DF,以便它最终在最终DF中.
在此先感谢您的任何帮助.
您发布的代码显示了一种生成减法表的巧妙方法.然而,它并没有发挥熊猫的优势.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]])
Run Code Online (Sandbox Code Playgroud)
您可以将其x视为一列df1和y一列df2.您将在下面看到,NumPy可以使用基本相同的语法以基本相同的方式处理所有列df1和所有列df2.
下面的代码定义orig和using_numpy.orig是您发布的代码,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
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
如何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,)
Run Code Online (Sandbox Code Playgroud)
该[:, np.newaxis]来增加了一个新的轴x在右侧,所以形状(10, 1).因此x[:, np.newaxis] - y,减去具有形状(10, 1)阵列的形状阵列(5,).
从表面上看,这没有意义,但是NumPy数组根据某些规则广播它们的形状以试图使它们的形状兼容.
第一条规则是可以在左侧添加新轴.因此,一系列形状(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]])
Run Code Online (Sandbox Code Playgroud)
所以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-axis与之互动100-axis.我们希望它们处于不同的轴上.
因此,如果我们添加一个这样的轴arr1:arr1[:,np.newaxis,:],那么它的形状就变成了
In [22]: arr1[:, np.newaxis, :].shape
Out[22]: (1000, 1, 4)
Run Code Online (Sandbox Code Playgroud)
现在,NumPy广播将两个阵列都推到了普通的形状(1000, 100, 4).瞧,减法表.
要将值按到形状的2D DataFrame中(1000*100, 4),我们可以使用reshape:
arr3 = arr3.reshape(-1, 4)
Run Code Online (Sandbox Code Playgroud)
该-1告诉NumPy的取代-1与被需要的任何正整数的重塑是有道理的.由于arr具有1000*100*4的值,因此-1将替换为1000*100.使用-1比写更好1000*100然而,因为它允许即使我们改变的行数的代码工作df1和df2.