我希望只在数字列中应用 fillna
,这是否可行?
现在,我正在所有列中应用它:
df = df.replace(r"^\s*$", np.nan, regex=True)
您可以选择数字列,然后填充缺失值。例如:
import pandas as pd
df = pd.DataFrame({'a': [1, None] * 3,
'b': [True, None] * 3,
'c': [1.0, None] * 3})
# select numeric columns
numeric_columns = df.select_dtypes(include=['number']).columns
# fill -1 to all NaN
df[numeric_columns] = df[numeric_columns].fillna(-1)
# print
print(df)
这是一个老问题,然而我发现单独填充每一列比当前选择的答案更快:
def func(df, value):
df = df.copy()
for col in df:
# select only integer or float dtypes
if df[col].dtype in ("int", "float"):
df[col] = df[col].fillna(value)
return df
func(df, value=-1) # or df.pipe(func, value=-1)
a b c
0 1.0 True 1.0
1 -1.0 None -1.0
2 1.0 True 1.0
3 -1.0 None -1.0
4 1.0 True 1.0
5 -1.0 None -1.0
loop
返回 470 µs ± 12.1 µs每个循环(平均值±7次运行的标准偏差,每个循环1000次)
,而接受的答案返回1.57 ms ± 26.3 µs每个循环(平均值±7次运行的标准偏差,每个循环1000次)
。pd.concat([df]*10_000, ignore_index=True)
,loop
返回1.48 ms ± 79.2 µs每个循环(平均值±7次运行的标准偏差,每个循环1000次)
,而选定的答案返回2.47 ms ± 140 µs每个循环(平均值±7次运行的标准偏差,每个循环100次)
。loop
比选定的答案快得多。当你试图提高性能时,这些信息可能会有所帮助。
np.select
会增加速度。 - Prayson W. Daniel