Python:pandas列中的部分字符串匹配,并从pandas数据帧中的其他列中检索值

时间:2020-09-23 12:00:58

标签: python pandas

我有一个file nameFile_Name = 23092020_indent.xlsx的字符串

现在我有一个数据框,如下所示:

Id   fileKey      fileSource    fileStringLookup
10   rel_ind      sap_indent       indent
20   dm_material   sap_mm          mater
30   dm_vendor     sap_vm          vendor

目标:找到fileKeyfileSource匹配的fileStringLookupfile name

不可能完全匹配,因此我们可以设置regex = True

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

if tbl_master_file['fileStringLookup'].str.contains(File_Name,regex=True):
    File_Key = np.where(tbl_master_file['fileStringLookup'].str.contains(File_Name,regex=True),\
                        tbl_master_file['fileKey'],'')
    File_Source = np.where(tbl_master_file['fileStringLookup'].str.contains(File_Name,regex=True),\
                        tbl_master_file['fileSource'],'')

但这不会为File_KeyFile_Source返回任何值。 相反,我收到以下错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我进一步调查了df['fileStringLookup'].str.contains(File_Name,regex=True)是否返回任何值为True的值。但是,即使返回False,它也会返回Id=10

我想要的输出:

File_Key = 'rel_ind'
File_Source = 'sap_indent'

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

您的错误是由于您对str.contains的调用返回了一系列布尔值,每个布尔值对应于原始系列的每个元素。因此,if语句不知道要检查什么,因为一系列布尔值的真值是不明确的。

我会在函数中使用pd.iterrows(),例如:

def get_filekey_filesource(filename, df):
   return [{"fileSource": data.loc["fileSource"],
            "fileKey": data.loc["fileKey"]}
           if filename in data.loc["fileStringLookup"]
           else {}
           for index, data in df.iterrows()]

如您所见,这将为您返回字典列表,其中键fileSourcefileKey保留匹配行的各自值,或匹配失败的空dic。

这看起来并不理想,但这是我能想到的最好的选择。欢迎反馈。