使用pandas isin()遇TypeError:传入字符串而非类列表对象的问题
问题解决:判断文件夹路径是否属于指定目录并修复isin()错误
需求说明
需要在pl_dest DataFrame中新增status列,判断Folder_Name_to_create列的文件夹路径是否是指定目录test的子目录(例如判断O:\Stack\Over\Flow\2010是否在O:\Stack\Over\Flow目录下)。
原DataFrame结构:
Folder_Name_to_create 0 O:\Stack\Over\Flow\2010 1 O:\Stack\Over\Flow\2011
原代码及错误
原代码:
import pandas as pd pl_dest = pd.DataFrame( {'Folder_Name_to_create': [r'O:\Stack\Over\Flow\2010', r'O:\Stack\Over\Flow\2011'] } ) test = (r'O:\Stack\Over\Flow') pl_dest['status'] = pl_dest['Folder_Name_to_create'].isin(test)
运行时触发错误:
TypeError: only list-like objects are allowed to be passed to isin(), you passed a [str]
错误原因
isin()方法要求传入列表、数组这类类列表可迭代对象,直接传单个字符串不符合参数要求,导致报错。- 更关键的是,
isin()的逻辑是判断元素是否完全匹配集合中的值,并不适合用来判断路径的包含关系——即使你把test改成列表,也无法实现“子目录判断”的需求。
正确解决方案
方法一:字符串前缀匹配(简单场景适用)
子目录的路径必然以父目录路径加路径分隔符开头,用str.startswith()可以实现判断,注意加上路径分隔符避免误判(比如防止O:\Stack\Over\Flow1被误判为O:\Stack\Over\Flow的子目录)。
代码:
import pandas as pd pl_dest = pd.DataFrame( {'Folder_Name_to_create': [r'O:\Stack\Over\Flow\2010', r'O:\Stack\Over\Flow\2011'] } ) test = r'O:\Stack\Over\Flow' # 拼接路径分隔符,确保匹配的是子目录而非前缀相似的路径 test_with_sep = test + '\\' pl_dest['status'] = pl_dest['Folder_Name_to_create'].str.startswith(test_with_sep)
运行结果:
Folder_Name_to_create status 0 O:\Stack\Over\Flow\2010 True 1 O:\Stack\Over\Flow\2011 True
方法二:用pathlib处理(复杂路径场景适用)
如果涉及相对路径、符号链接等复杂情况,使用pathlib模块进行路径解析和判断更严谨,能确保路径关系的准确性。
代码:
import pandas as pd from pathlib import Path pl_dest = pd.DataFrame( {'Folder_Name_to_create': [r'O:\Stack\Over\Flow\2010', r'O:\Stack\Over\Flow\2011'] } ) test_path = Path(r'O:\Stack\Over\Flow') def is_subpath(child_path_str): child_path = Path(child_path_str) try: # resolve()解析符号链接、相对路径为绝对路径,确保对比的准确性 child_path.resolve().relative_to(test_path.resolve()) return True except ValueError: # 若不是子路径会抛出ValueError,返回False return False pl_dest['status'] = pl_dest['Folder_Name_to_create'].apply(is_subpath)
这个方法能处理绝大多数路径场景,避免字符串匹配可能带来的误判。
内容的提问来源于stack exchange,提问作者Jonnyboi
相关产品推荐
相关产品推荐

