python - 如何将带有 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.
解决方案
在一行中不使用 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
推荐阅读
- java - 从另一个列表中查找(自定义)列表中的对象
- c - uint8_t* - 指向 RGB 图像地址的指针
- java - Java:如何在不使用 Sort() 的情况下基于自定义对象 ArrayList 创建排序字符串 ArrayList
- python - 如何将抓取的数据发送到 postgresql 数据库
- bash - 如何在 s-nail 中设置 Content-Type?
- javascript - React Google Maps 不导入
- xml - 优化 Spark Scala 作业 - 许多任务、需要数小时的嵌套映射、XML 解析
- python - 如何在 Earth Explorer 的 API 请求中正确使用 POST
- powershell - 如何在powershell中拦截WM_QUIT?
- python - 生成与给定数组 x 相关的随机数 - 指定相关性并生成数字