目标:
我想使用 python 以有效的方式合并两个具有容差的数据帧 df1 和 df2。 df1 的形状为 (l, 2),df2 的形状为 (p, 13),其中 l < m < p。 形状为 (m, 13) 的目标数据框 df3 应该包含公差范围内的所有匹配项,而不仅仅是最接近的匹配项。
我想将 df1 的 Col0 与 df2 的 Col2 合并,容差为“tolerance”。
例子:
df1:
Index, Col0, Col1
0, 1008.5155, n01
df2:
Index, Col0, Col1, Col2, Col3, Col4, Col5, Col6, ...
0, 0, 0, 510.0103, k03, 0, k05, k06, ...
1, 0, 0, 1007.6176, k13, 0, k15, k16, ...
2, 0, 0, 1008.6248, k123, 0, k25, k26, ...
df3:
Index, Col0, Col1, Col2, Col3, Col4, Col5, Col6, ...
0, 1008.5155, 0.8979, 1007.6176, k03, n01, k05, k06, ...
1, 1008.5155, 0.1093, 1008.6248, k13, n01, k15, k16, ...
为了形象化,df3 的 col1 给出了 df1 和 df2 各自值的差异。因此,它必须小于公差。
我当前的解决方案需要花费大量时间并需要大量内存。
# Create empty list to collect matches
df3_list = []
df3_array = np.asarray(df3_list)
# loops to find matches. Fills array with matches
df3_row = np.asarray([0.0, 0.0, 0.0, 0.0, 0.0, 0, 0, 0, 0, 0, 0, 0, 0])
for n in range(len(df1)):
for k in range(len(df2)):
if abs(df1.iloc[n,0]-df2.iloc[k,2]) < tolerance:
df3_row[0] = df1.iloc[n,0]
df3_row[1] = abs(df1.iloc[n,0]-df2.iloc[k,2])
df3_row[2] = df2.iloc[k,2]
df3_row[3] = df2.iloc[k,3]
df3_row[4] = df1.iloc[n,1]
df3_row[5] = df2.iloc[k,5]
.
.
.
df3_array = np.append(df3_array, df3_row)
# convert list into dataframe
df3 = pd.DataFrame(df3_array.T.reshape(-1,13), columns = header)
我也尝试过一次获得两个索引
[[n, k] for n, k in zip(range(len(df1)), range(len(df2))) if abs(df1.iloc[n,0]-df2.iloc[k,2]) < tolerance]
但是,它只给我一个空数组,所以我做错了。
对于各自的数组,我也尝试过使用
np.nonzero(np.isclose(df2_array[:, 2], df1_array[:,:,None], atol=tolerance))[-1]
但是,np.isclose + np.nonzero 只得到了 df2 的索引,而且比我的循环密集型方法多得多。没有 df1 的相应索引,我有点迷路了。 我认为最后一种方法是最有前途的,但我似乎无法合并数据集,因为这些值并不完全匹配,而且最接近的匹配并不总是正确的解决方案。有什么想法可以解决这个问题吗?
请您参考如下方法:
你需要把这个问题分成几个部分
- 找到相应的收盘指数
- 在这些索引上加入 DataFrames
- 做你的额外计算
查找索引
使用 np.isclose,这是一个非常简单的生成器函数,它生成一个包含 df1 和 df2 索引的 DataFrame df1
def find_close(df1, df1_col, df2, df2_col, tolerance=1):
for index, value in df1[df1_col].items():
indices = df2.index[np.isclose(df2[df2_col].values, value, atol=tolerance)]
s = pd.DataFrame(data={'idx1': index, 'idx2': indices.values})
yield s
然后我们可以轻松地将它们连接起来以使用包含不同索引的辅助 DataFrame。
df_idx = pd.concat(find_close(df1, 'Col0', df2, 'Col2'), ignore_index=True)
为了测试这一点,我向 df1 添加了第二条记录
df1_str = '''Index, Col0, Col1
0, 1008.5155, n01
1, 510, n03'''
idx1 idx2 0 0 1 1 0 2 2 1 0
加入数据框
使用 pd.merge
df1_close = pd.merge(df_idx, df1, left_on='idx1', right_index=True).reindex(columns=df1.columns)
df2_close = pd.merge(df_idx, df2, left_on='idx2', right_index=True).reindex(columns=df2.columns)
df_merged = pd.merge(df1_close, df2_close, left_index=True, right_index=True)
Col0_x Col1_x Col0_y Col1_y Col2 Col3 Col4 Col5 Col6 ... 0 1008.5155 n01 0 0 1007.6176 k13 0 k15 k16 ... 1 1008.5155 n01 0 0 1008.6248 k123 0 k25 k26 ... 2 510.0 n03 0 0 510.0103 k03 0 k05 k06 ...
做额外的计算
您需要重命名一些列,并分配它们之间的差异,但这应该是微不足道的
