python:如何提高合并两个DataFrame的速度?

标签 python pandas performance dataframe

我有两个名为 ab 的 DataFrame。 a 的所有列都应与 DataFrame bkeyB 列匹配。我定义了一个 match 函数来实现它,但是代码的速度很低,因为 ab 的 DataFrame 实际上具有更大的形状。所以现在我想提高匹配两个DataFrame的速度。

import pandas as pd
import time

start=time.time()
a=pd.DataFrame({'key1':[1,5,1],'key2':[1,2,11]})
b=pd.DataFrame({'keyB':[1,2,3,4,5],'other':['q','q','w','w','r']})

def match(num,a,b,col):
    aFeat=a.iloc[num:num+1]
    bFeat=b[b['keyB'].isin([a[col].loc[num]])]
    aFeat.reset_index(drop=True,inplace=True)
    bFeat.reset_index(drop=True,inplace=True)
    new=pd.concat([aFeat,bFeat],axis=1)
    return new

newb=pd.DataFrame({})
for col in ['key1','key2']:
    newa=pd.DataFrame({})
    for num in range(len(a)):
        newa=pd.concat([newa,match(num,a,b,col)],axis=0)
    newa.reset_index(drop=True,inplace=True)
    del newa[col]
    newb.reset_index(drop=True,inplace=True)
    newb=pd.concat([newb,newa],axis=1)
    newb = newb.rename(columns={'keyB': 'keyB_'+col, 'other': 'other_'+col})

print(newb)
end=time.time()
print('time:',end-start)

输入:

a    key1  key2
0     1     1
1     5     2
2     1    11

b    keyB other
0     1     q
1     2     q
2     3     w
3     4     w
4     5     r

输出:

   key2  keyB_key1 other_key1  key1  keyB_key2 other_key2
0     1          1          q     1        1.0          q
1     2          5          r     5        2.0          q
2    11          1          q     1        NaN        NaN

使用时间:

time: 0.015628576278686523

希望获得有关提高代码性能的建议。

最佳答案

您可以使用mapb 在循环中创建的 Series 将每个 Series 附加到列表和最后 concat全部在一起:

s = b.set_index('keyB')['other']
print (s)
keyB
1    q
2    q
3    w
4    w
5    r
Name: other, dtype: object

dfs = []
for col in ['key1','key2']:
    dfs.append(a[col])
    val = a[col].map(s).rename('other_' + col)
    dfs.append(pd.Series(np.where(val.notnull(), a[col], np.nan), name='keyB_' + col))
    dfs.append(val)

df = pd.concat(dfs, axis=1)
print (df)
   key1  keyB_key1 other_key1  key2  keyB_key2 other_key2
0     1        1.0          q     1        1.0          q
1     5        5.0          r     2        2.0          q
2     1        1.0          q    11        NaN        NaN

另一个解决方案 merge在列表理解中和 concat :

dfs = [b.merge(a[[col]], left_on='keyB', right_on=col)
        .rename(columns={'keyB':'keyB_'+col,'other':'other_'+col}) for col in ['key1','key2']]
df = pd.concat(dfs, axis=1)
print (df)
   keyB_key1 other_key1  key1  keyB_key2 other_key2  key2
0          1          q     1        1.0          q   1.0
1          1          q     1        2.0          q   2.0
2          5          r     5        NaN        NaN   NaN

关于python:如何提高合并两个DataFrame的速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52326479/

相关文章:

Python C-ext 命名空间与常规 python 子模块混合?

python - 如何更改 DataFrame 中一列的数据类型?

linux - 以特定速度执行 stdout 输出

mysql - HQL/MySQL 用于列出不同项和重复项

Python正则表达式捕获各种url模式组

python - 什么时候在python中释放函数堆栈数据?

python - `type` 和 `tuple` 的子类

python - 如何合并具有来自多列的重复值的行

Python - 带有数组到 csv 文件的字典

performance - fseek()如何在文件系统中实现?