【问题标题】:Python, Isin, TypeError: only list-like objects are allowed to be passed to isin(), you passed a [str]Python, Isin, TypeError: only list-like objects are allowed be passed to be passed to isin(), 你传递了一个[str]
【发布时间】:2022-11-12 13:46:43
【问题描述】:

我正在尝试创建一个列status,以显示我的DataFrame 值是否在我的目录test 中。例如文件夹O:\Stack\Over\Flow\2010 是否存在于O:\Stack\Over\Flow 目录中。

我的pl_dest 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 想要一个列表,而你给了它一个字符串。你试过给它一个清单吗? (另外,请将数据/代码作为文本发布,not as images。)
  • 如果你想让test 成为一个元组,它需要一个尾随逗号test = (r'O:\Stack\Over\Flow',),或者如果你想创建一个列表使用方括号test = [r'O:\Stack\Over\Flow']
  • 好吧,我列出了test。代码现在可以工作了!虽然我的status 列仍然显示错误!我认为这是因为我需要 test 来读取我的文件目录,而不仅仅是使用O:\Stack\Over\Flow 。我在想isin 可能不适合检查目录O:\Stack\Over\Flowpl_dest 值。

标签: python pandas


【解决方案1】:

您可以使用pathlib 来检查使用pathlib.Path.is_dir() 的目录是否存在。如果将其包装在基本函数中,则可以将其与 df.apply() 一起使用

由于您的数据框具有您要检查的完整路径,因此您根本不需要 test,我不认为。

import pathlib

def my_func(test_path: str) -> bool:
    p = pathlib.Path(test_path)
    return p.is_dir()

pl_dest['status']  = pl_dest['Folder_name_to_create'].apply(my_func)

【讨论】:

    【解决方案2】:

    遍历行并检查存在

    from pathlib import Path
    import os
    import pandas as pd
    
    status=[]
    
    for index, row in df.iterrows():
        path = row['Folder_Name_to_create']
        path=Path(path)
        if os.path.isdir(path):
           status.append('File_exists')
        else:
           status.append('File_not_exists')
    
    df['status']=status
    

    预期输出#

    Folder_Name_to_create    status 
    c://:path/example        File_exists
    c://:path/example2       File_not_exists
    

    注意:未测试...只是发布执行方式...试试这个让 我知道

    【讨论】:

    • 谢谢,df 应该是pl_dest 吗?我的test 路径是如何被拾取的?
    • 是的.....相应地重命名
    • OP 检查的路径看起来都是目录,而不是文件,所以你可能想要os.path.isdir() 而不是...isfile()
    • 已编辑!!..谢谢@scotscotmcc
    猜你喜欢
    • 1970-01-01
    • 2019-12-15
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2022-12-28
    • 2023-02-25
    • 1970-01-01
    • 2021-04-26
    相关资源
    最近更新 更多