Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.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 使用for循环在列表中搜索值并打印搜索结果_Python_Pandas - Fatal编程技术网

Python 使用for循环在列表中搜索值并打印搜索结果

Python 使用for循环在列表中搜索值并打印搜索结果,python,pandas,Python,Pandas,我正在有许多子文件夹的文件夹中搜索文档。我用这个 def find_all(name, path): result = [] for root, dirs, files in os.walk(path): if name in files: result.append(os.path.join(root, name)) print(result) find_all(name, "path_here") 然后,我在excel中有

我正在有许多子文件夹的文件夹中搜索文档。我用这个

def find_all(name, path):
   result = []
   for root, dirs, files in os.walk(path):
      if name in files:
         result.append(os.path.join(root, name))
   print(result)
find_all(name, "path_here")
然后,我在excel中有一个要在文件夹中搜索的文档名列表

d = {'doc_id': [123456, 289456, 654987, 128984, 980524]}
df = pd.DataFrame(data=d)

我想使用
for循环
来迭代每个
doc\u id
,并使其成为
find\u all
函数中的
name
变量

for doc in df:
   name = doc
我不知道如何将这两个部分组合在一起,并在每个doc_id旁边的新列中打印结果。 所以结果可能是这样的

df
doc_id     result
123456      n/a
289456     "folder named here that doc was found in"
654987      n/a
128984     "folder named here that doc was found in"
980524     "folder named here that doc was found in"
这应该起作用:

l=[i for i in os.walk('your_main_path_here')]

def path_of_file(file):
    for i in l:
        if file in i[2]:
            return i[0]
    return 'n/a'

df['result']=''
for i in range(len(df)):
    df.result.iloc[i]=path_of_file(df.doc_id.iloc[i])
或者,新列可以用以下两种方式填充(如果数据帧太长,建议使用):

适用于:

df['result']=df['doc_id'].apply(lambda x: path_of_file(x))
带地图:

df['result']=[i for i in map(path_of_file, df['doc_id'])]

for doc in df['doc_id']
将在您的情况下工作。如果您的函数不
返回任何内容,那么您将得到一列
None
,或者您必须执行一些奇怪的操作,例如将
print()
语句的结果管道化到字符串,然后将该字符串分配到数据帧。此外,在pandas中,迭代数据帧值几乎从来都不是最好的选择,请研究使用
apply()
将函数应用于数据帧
df['result']
for loop
是否进入
name\u path
函数内部?请稍等,我会返回完整的解决方案。你能确认你想要的是第二列,第一列中的每个文件都有文件路径吗?是的,就是这样。出于好奇,你为什么要用
来表示范围内的i(len(df)):
iloc
而不是内置的
apply()
将函数应用于数据帧?是的,我也添加了此选项,以及映射选项,以防df太长