首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用应用lambda检查条件时,级数的真值不明确

使用应用lambda检查条件时,级数的真值不明确
EN

Stack Overflow用户
提问于 2021-02-20 02:54:49
回答 2查看 43关注 0票数 2

我正在尝试从列中剥离逗号,稍后我会将其转换为数字,并希望我能得到一些关于此错误的建议。

我已经定义了要对其执行str.replace操作的列。我可以使用相同的方法删除空格,没有问题,但是当我运行下面的代码时,我得到了以下错误:

代码语言:javascript
复制
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

这是我的代码。感谢你在我如何误用lambda函数方面的一些指点。

代码语言:javascript
复制
numeric_cols = ['Doses – AZ/SII (indicative distribution)',
               'Doses – AZ/SKBio (indicative distribution)',
               'Doses – Pfizer-BioNTech (exceptional allocation)']

df = df.apply(lambda x: x.str.strip() if x.dtype == "object" else x)
df = df.apply(lambda x: x.str.replace(',', '') if x in numeric_cols else x)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-02-20 03:23:53

您可以使用helper函数执行此操作,如下所示:

代码语言:javascript
复制
import pandas as pd

cols = ['AZ/SII','AZ/SKBio','Pfizer-BioNTech','non-numeric']
df = pd.DataFrame([['3,2', '4,5', '5,6', 'a,b,c,d'], ['5,','3,2','4,7','a,f,r,h']], columns= cols)
print(f'Before stripping: \n{df}\n')

def remove_comma(row):
    numeric_cols = ['AZ/SII', 'AZ/SKBio', 'Pfizer-BioNTech']
    for col in numeric_cols:
        row[col] = row[col].replace(',','')
    return row

df = df.apply(lambda x: x.str.strip() if x.dtype == "object" else x)
df = df.apply(lambda row: remove_comma(row), axis = 1)
print(f'After stripping: \n{df}\n')

#output:
Before stripping: 
  AZ/SII AZ/SKBio Pfizer-BioNTech non-numeric
0    3,2      4,5             5,6     a,b,c,d
1     5,      3,2             4,7     a,f,r,h

After stripping: 
  AZ/SII AZ/SKBio Pfizer-BioNTech non-numeric
0     32       45              56     a,b,c,d
1      5       32              47     a,f,r,h
票数 2
EN

Stack Overflow用户

发布于 2021-02-20 03:39:37

这也是一个选项

代码语言:javascript
复制
for col in numeric_cols:
    df[col] = df[col].str.replace(',', '')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66283472

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档