如何在Pandas中对多列应用自定义函数?解决KeyError问题
Hey there! That KeyError is popping up because of a tiny syntax misstep in how you're selecting multiple columns in Pandas. Let's break it down and fix it right away.
错误原因
When you write df["Passengers", "Revenue", "Cost"], Pandas treats the tuple ("Passengers", "Revenue", "Cost") as a single column name—and since you don't have a column with that exact weird name, it throws a KeyError. To pick multiple columns correctly, you need to wrap the column names in a list and use double square brackets.
正确实现方式
Here are two solid ways to apply your cleaning function to those columns:
1. 使用apply(适合处理整列的函数)
If your convert_dash_comma_into_float function is built to work with an entire Series (a full column), use double brackets to select the columns first, then apply the function. Don't forget to assign the result back to the original DataFrame to save your changes:
df[["Passengers", "Revenue", "Cost"]] = df[["Passengers", "Revenue", "Cost"]].apply(convert_dash_comma_into_float)
2. 使用applymap(适合处理单个单元格的函数)
Most cleaning functions like yours operate on individual values (e.g., turning strings like "1,234" or "-" into floats). In this case, applymap is the better choice—it applies the function to every single cell in the selected columns:
df[["Passengers", "Revenue", "Cost"]] = df[["Passengers", "Revenue", "Cost"]].applymap(convert_dash_comma_into_float)
示例函数参考
Just to make sure we're on the same page, here's what your cleaning function might look like (tweak it to match your specific data format):
def convert_dash_comma_into_float(value): # Replace dashes with 0 (or use "" if you want NaN instead) # Swap commas for decimal points to make float conversion work if isinstance(value, str): cleaned_value = value.replace("-", "0").replace(",", ".") return float(cleaned_value) # Return non-string values as-is (like already numeric entries) return value
内容的提问来源于stack exchange,提问作者Hannan

