删除所有列值,但检查是否存在任何元组

问题描述 投票:0回答:1

我有多个数据框,它们使用相同的函数来删除所有值。然而,有些值是元组,每当我遇到剥离元组时它就会抛出错误。

我的函数如下所示:

for col in df.columns:
        if df[col].dtype == 'object':   
            df[col] = df[col].apply(lambda x: str(x).strip())

我有另一个针对特定数据框的函数,该数据框始终具有元组:

for col in df.columns:
        if df[col].dtype == 'object':   
            df[col] = df[col].apply(lambda x: str(x).strip())

    df['Commodity'] = [(x.strip() for x in ls) for ls in df['Commodity'].values]
    df['Commodity'] = df['Commodity'].apply(sorted)

第二个函数在到达 Commodity 列时总是会抛出错误,因为它不会处理元组。我该如何处理第一个函数中的特定情况?

python pandas
1个回答
1
投票

像这样的东西怎么样:

for col in df.columns:
        if df[col].dtype == 'object':   
            df[col] = df[col].apply(lambda x: str(x).strip() if isinstance(x, str)
                                              else (s.strip() for s in x))
© www.soinside.com 2019 - 2024. All rights reserved.