[英]Convert a lambda function to a regular function
I'm trying to understand how can I convert a lambda function to a normal one.我想了解如何将 lambda function 转换为普通的。 I have this lambda function that it supposed to fill the null values of each column with the mode
我有这个 lambda function 它应该用模式填充每列的 null 值
def fill_nn(data):
df= data.apply(lambda column: column.fillna(column.mode()[0]))
return df
I tried this:我试过这个:
def fill_nn(df):
for column in df:
if df[column].isnull().any():
return df[column].fillna(df[column].mode()[0])
Hi Hope you are doing well!嗨希望你做得很好!
If I understood your question correctly then the best possible way will be similar to this:如果我正确理解了您的问题,那么最好的方法将与此类似:
import pandas as pd
def fill_missing_values(series: pd.Series) -> pd.Series:
"""Fill missing values in series/column."""
value_to_use = series.mode()[0]
return series.fillna(value=value_to_use)
df = pd.DataFrame(
{
"A": [1, 2, 3, 4, 5],
"B": [None, 2, 3, 4, None],
"C": [None, None, 3, 4, None],
}
)
df = df.apply(fill_missing_values) # type: ignore
print(df)
# A B C
# 0 1 2.0 3.0
# 1 2 2.0 3.0
# 2 3 3.0 3.0
# 3 4 4.0 4.0
# 4 5 2.0 3.0
but personally, I would still use the lambda
as it requires less code and is easier to handle (especially for such a small task).但就个人而言,我仍然会使用
lambda
,因为它需要的代码更少并且更容易处理(尤其是对于这样的小任务)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.