Python 正在寻找加速熊猫合并的方法(或可能的其他方法)
您好,我最近发布了一个关于执行合并的问题,以便获取熊猫数据帧并返回满足条件的列 详细信息可在此处找到: (不确定我是否应该发布整个问题以保持此帖子的独立性,所以我现在只留下一个链接) 给出的解决方案效果很好,因为我需要更小的数据集,所以我想不到1000行 以下是建议的答案:Python 正在寻找加速熊猫合并的方法(或可能的其他方法),python,python-3.x,pandas,dataframe,pandas-groupby,Python,Python 3.x,Pandas,Dataframe,Pandas Groupby,您好,我最近发布了一个关于执行合并的问题,以便获取熊猫数据帧并返回满足条件的列 详细信息可在此处找到: (不确定我是否应该发布整个问题以保持此帖子的独立性,所以我现在只留下一个链接) 给出的解决方案效果很好,因为我需要更小的数据集,所以我想不到1000行 以下是建议的答案: m=(df1.assign(key=1).merge(df2.assign(key=1),on='key',suffixes=('','_y')).drop('key', 1)
m=(df1.assign(key=1).merge(df2.assign(key=1),on='key',suffixes=('','_y')).drop('key', 1)
.query("(Code==Code_y)&(Price<=Price_y)"))
m.groupby(['Code','Price'],sort=False)['Price_y'].first().reset_index(name='New Price'
m=(df1.assign(key=1).合并(df2.assign(key=1),on='key',后缀=('',u'y')).删除('key',1)
.query(“(Code==代码y)&(Price请尝试:
m=df1.set_index('Code').join(df2.set_index('Code'),rsuffix='_New')
df1.join(m[m.Price<=m.Price_New].groupby('Price',sort=False)['Price_New']
.first().reset_index(drop=True))
在样本df上的性能:
考虑以下问题的替代解决方案。在这里,我们迭代不同的code
值,并为每个Price
搜索合适的新价格。在时间和内存上应该比原来的方法更有效。此外,通过优化和/或numba
可以提高效率
import numpy as np
import pandas as pd
def get_all_new(pd_series, result):
result[pd_series.name] = np.sort(pd_series.unique())
def find_new_group(pd_series, sorted_arrays):
return pd_series.apply(lambda x: find_new(x, sorted_arrays[pd_series.name]))
def find_new(value, sorted_array):
pos = np.searchsorted(sorted_array, value)
return sorted_array[pos] if pos < sorted_array.size else None # None OR value ???
if __name__ == '__main__':
N1, N2, M1, M2 = 5, 5, 5, 5
df1 = pd.DataFrame(
{'Code': ['X'] * N1 + ['Y'] * N2,
'Price': np.random.randint(1, 100, N1 + N2) / 10})
df2 = pd.DataFrame(
{'Code': ['X'] * M1 + ['Y'] * M2,
'Price': np.random.randint(1, 100, M1 + M2) / 10})
print(df1)
print(df2)
all_new = dict()
# collect all new prices for every Code
df2.groupby('Code')['Price'].apply(lambda x: get_all_new(x, all_new))
# find appropriate new price for every old price
df1['New Price'] = df1.groupby('Code')['Price'].apply(lambda x: find_new_group(x, all_new))
print(df1)
用N1、N2、M1、M2=…
100\u 000
-518 ms±2.25 ms/圈(7次运行的平均值±标准偏差,每个循环1次)
,
1\u 000\u 000
-5.29 s±72.6 ms/循环(平均±标准偏差为7次运行,每个循环1次)
确保正确配置数据类型,仅从数据帧中提取必要字段,并在运行中清理未使用的数据帧。
import numpy as np
import pandas as pd
def get_all_new(pd_series, result):
result[pd_series.name] = np.sort(pd_series.unique())
def find_new_group(pd_series, sorted_arrays):
return pd_series.apply(lambda x: find_new(x, sorted_arrays[pd_series.name]))
def find_new(value, sorted_array):
pos = np.searchsorted(sorted_array, value)
return sorted_array[pos] if pos < sorted_array.size else None # None OR value ???
if __name__ == '__main__':
N1, N2, M1, M2 = 5, 5, 5, 5
df1 = pd.DataFrame(
{'Code': ['X'] * N1 + ['Y'] * N2,
'Price': np.random.randint(1, 100, N1 + N2) / 10})
df2 = pd.DataFrame(
{'Code': ['X'] * M1 + ['Y'] * M2,
'Price': np.random.randint(1, 100, M1 + M2) / 10})
print(df1)
print(df2)
all_new = dict()
# collect all new prices for every Code
df2.groupby('Code')['Price'].apply(lambda x: get_all_new(x, all_new))
# find appropriate new price for every old price
df1['New Price'] = df1.groupby('Code')['Price'].apply(lambda x: find_new_group(x, all_new))
print(df1)
Code Price
0 X 7.8
1 X 6.6
2 X 3.2
3 X 0.3
4 X 4.7
5 Y 0.5
6 Y 1.1
7 Y 8.9
8 Y 6.7
9 Y 0.5
Code Price
0 X 6.9
1 X 4.6
2 X 2.3
3 X 7.6
4 X 2.4
5 Y 0.8
6 Y 3.4
7 Y 0.4
8 Y 4.2
9 Y 9.6
Code Price New Price
0 X 7.8 NaN
1 X 6.6 6.9
2 X 3.2 4.6
3 X 0.3 2.3
4 X 4.7 6.9
5 Y 0.5 0.8
6 Y 1.1 3.4
7 Y 8.9 9.6
8 Y 6.7 9.6
9 Y 0.5 0.8