在python中使用pandas加速类似vlookup的操作

2024-06-16 12:35:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编写了一些代码,基本上对两个pandas数据帧执行excel风格的vlookup,并希望加快速度。在

数据帧的结构如下: 数据库1_数据框列:
'VALUE'、'COUNT'、'GRID'、'SGO10GEO'

合并_数据框列:
“网格”、“ST0”、“ST1”、“ST2”、“ST3”、“ST4”、“ST5”、“ST6”、“ST7”、“ST8”、“ST9”、“ST10”

sgo公司_数据框列:
'mkey','类型'

为了合并它们,我做了以下操作:
1对于dbase1_df中的每一行,查找其“SGO10GEO”值与sgo_df的“mkey”值匹配的行。从sgo_df的该行中获取“type”。在

  1. “type”包含从0到10的整数。通过在类型中附加'ST'来创建列名。

  2. 在merged_df中找到值,其中它的“GRID”值与dbase1_df中的“GRID”值匹配,列名是我们在步骤2中获得的。将此值输出到csv文件中。

//将dbase1 dbf读入数据帧

dbase1_df=pandas.DataFrame.from\u csv(dbase1_文件,index_col=False)
合并的_df=pandas.DataFrame.from\u csv('合并.csv',索引_col=False)

卢普_写出来的([“值”,“类型”,提取_变量上限()])
//对于dbase1数据帧中的每个唯一值:
对于索引,dbase1中的行_数据框错误():

# 1. Find the soil type corresponding to the mukey
tmp  = sgo_df.type.values[sgo_df['mkey'] == int(row['SGO10GEO'])]
if tmp.size > 0:        
    s_type = 'ST'+tmp[0]
    val       = int(row['VALUE'])            

    # 2. Obtain hmu value
    tmp_val  = merged_df[s_type].values[merged_df['GRID'] == int(row['GRID'])] 
    if tmp_val.size > 0:
        hmu_val = tmp_val[0]             
        # 4. Output into data frame: VALUE, hmu value
        lup_out.writerow([val,s_type,hmu_val])
    else:
        err_out.writerow([merged_df['GRID'], type, row['GRID']])

这里有什么可能是速度瓶颈吗?目前,在dbase1_df中大约需要20分钟来处理大约500000行;在merged_df中大约需要1000行,在sgo_df中需要大约500000行。在

谢谢!在


Tags: csv数据pandasdfvaluetypevalmerged
1条回答
网友
1楼 · 发布于 2024-06-16 12:35:09

您需要在Pandas中使用merge操作以获得更好的性能。我无法测试以下代码,因为我没有数据,但至少它应该有助于您获得想法:

import pandas as pd

dbase1_df = pd.DataFrame.from_csv('dbase1_file.csv',index_col=False)
sgo_df = pd.DataFrame.from_csv('sgo_df.csv',index_col=False)
merged_df = pd.DataFrame.from_csv('merged_df.csv',index_col=False)

#you need to use the same column names for common columns to be able to do the merge operation in pandas , so we changed the column name to mkey

dbase1_df.columns = [u'VALUE', u'COUNT', u'GRID', u'mkey']

#Below operation merges the two dataframes
Step1_Merge = pd.merge(dbase1_df,sgo_df)

#We need to add a new column to concatenate ST and type
Step1_Merge['type_2'] = Step1_Merge['type'].map(lambda x: 'ST'+str(x))

# We need to change the shape of merged_df and move columns to rows to be able to do another merge operation
id = merged_df.ix[:,['GRID']]
a = pd.merge(merged_df.stack(0).reset_index(1), id, left_index=True, right_index=True)

# We also need to change the automatically generated name to type_2 to be able to do the next merge operation
a.columns = [u'type_2', 0, u'GRID']


result = pd.merge(Step1_Merge,a,on=[u'type_2',u'GRID'])

相关问题 更多 >