Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中执行等效的Excel索引匹配_Python_Pandas_Dataframe - Fatal编程技术网

如何在Python中执行等效的Excel索引匹配

如何在Python中执行等效的Excel索引匹配,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个问题,关于如何执行使用Excel中的索引匹配函数返回值并在Python中应用它的等效操作 作为一个在大型数据集上执行数据分析和操作的Excel用户,为了提高效率,我已经转向Python。我试图做的是根据从存储在字典中的值返回的值填充pandas数据帧中的列单元格 为此,我使用了以下代码: # imported csv DataFrames crew_data = pd.read_csv(r'C:\file_path\crew_data.csv') export_template =

我有一个问题,关于如何执行使用Excel中的索引匹配函数返回值并在Python中应用它的等效操作

作为一个在大型数据集上执行数据分析和操作的Excel用户,为了提高效率,我已经转向Python。我试图做的是根据从存储在字典中的值返回的值填充pandas数据帧中的列单元格

为此,我使用了以下代码:

# imported csv DataFrames

crew_data = pd.read_csv(r'C:\file_path\crew_data.csv') 

export_template = pd.read_csv(r'C:\file_path\export_template.csv')

#contract number dictionary

contract = {'Northern':'046-2019',
            'Southern':'048-2015D',}

#function that attempts to perform a INDEX MATCH equivalent 
def contract_num():

    for x, y in enumerate(crew_data.loc[:, 'Region']):

            if y in contract.keys():

                num = contract[y]

            else:

                print('ERROR')

    return(num)

#for loop which prepares then exports the load data

for i, r in enumerate(export_template):

    export_template.loc[:, 'Contract'] = contract_num()

export_template.to_csv(r'C:\file_path\export_files\UPLOADER.csv')

print(export_template)
总结本准则的目的如下:

  • contract_num函数中包含的for循环首先遍历crew_数据帧中的Region列
  • 如果数据帧中的值y与合同字典中的键匹配(注意:Region列仅包含两个值,'Southern'和'Northern'),它将从合同字典中的值返回相应的值
  • 准备然后导出加载数据的for循环调用contract_num()函数来填充export_template数据框中的contract列
  • 请注意,此循环中填充了116个额外的列,这些列已从上述代码中排除,以节省空间

    当代码被执行时,它会产生预期的结果,然而,问题是当在第二个for循环中调用函数时,它只返回一个值048-2015D,而不是对应于正确区域的值

    如前所述,这通常是在Excel中使用索引匹配来执行的,但是这样做不如使用上述脚本那样有效

    作为一个初学者,我怀疑示例代码可能看起来是欺骗和不必要的,并且可以使用更简洁的方法来执行

    如果有人能提供解决方案或指导,我们将不胜感激

    df=pd.DataFrame({'Region':['Northern'、'Northern'、'Northern',
    “北部”、“南部”、“南部”,
    “北部”、“东部”]})
    合同={'Northern':'046-2019',
    ‘南方’:‘048-2015D’}
    #类似于索引匹配
    df['Contract']=df.Region.map(合同)
    
    输出:

    如果合同不匹配,您可以添加打印:

    如果df.Contract.isna().any():
    打印(“错误”)
    
    或作出断言:

    assert not df.Contract.isna().any(),“找到空的合同字段”
    
    在这种情况下:

    AssertionError:找到空的合同字段
    
    hi,将此作为指导,以生成可复制的示例。
         Region   Contract
    0  Northern   046-2019
    1  Northern   046-2019
    2  Northern   046-2019
    3  Northern   046-2019
    4  Southern  048-2015D
    5  Southern  048-2015D
    6  Northern   046-2019
    7   Eastern        NaN