首页 > 解决方案 > 如何将带有 if 语句的函数同时应用于多个数据框列

问题描述

我有一个由多列中的数字字符串和/或空字符串组成的数据框,我想将这些列从字符串转换为“int”数据类型。在这样做之前,我想将空字符串转换为“-1”(int 或 -1 的字符串版本;没关系)。

我正在尝试同时将 lambda 函数应用于多个列以转换空字符串,但出现错误“'系列的真值不明确。使用 a.empty、a.bool()、a.item() , a.any() 或 a.all().', '发生在索引温度 (F)'"

我在下面发布了一个虚拟示例,说明我正在尝试使用我的实际数据框做什么,但它不起作用。当然,有一种在“for”循环中遍历每一列的解决方法,但我怀疑有一个更清洁的解决方案。

df = pd.DataFrame({'Temperature(F)':['30','40',''],'Gust':['','5','10']})
numericCols = ['Temperature(F)','Gust']
df[numericCols]=fTable[numericCols].apply(lambda x:-1 if x=='' else x)
df[numericCols] = fTable[numericCols].astype('int')
'''

As described, I get the error message "'The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index Temperature(F)'" when I run this.

标签: pythonpandasdataframelambda

解决方案


在一行中不使用 apply

df[numericCols].apply(pd.to_numeric, errors='coerce').fillna(value=-1)
# Out:
#    Temperature(F)  Gust
# 0            30.0  -1.0
# 1            40.0   5.0
# 2            -1.0  10.0

推荐阅读