我在Pandas 身上有这样的代码:
df[col] = (
df[col]
.fillna(method="ffill", limit=1)
.apply(lambda x: my_function(x))
)
我想用Polars重写这篇文章.
我试过这个:
df = df.with_columns(
pl.col(col)
.fill_null(strategy="forward", limit=1)
.apply(lambda x: my_function(x))
)
它不能正常工作.它填充了前进策略,但忽略了使用我定义的函数填充缺失的值.我应该在代码中更改什么才能获得我想要的东西?
试试这个代码:
df_polars = pl.DataFrame(
{"A": [1, 2, None, None, None, None, 4, None], "B": [5, None, None, None, None, 7, None, 9]}
)
df_pandas = pd.DataFrame(
{"A": [1, 2, None, None, None, None, 4, None], "B": [5, None, None, None, None, 7, None, 9]}
)
last_valid_data: int
def my_function(x):
global last_valid_data
if x == None or np.isnan(x):
result = last_valid_data * 10
else:
last_valid_data = x
result = x
return result
col = "A"
last_valid_data = df_pandas[col][0]
df_pandas[col] = df_pandas[col].fillna(method="ffill", limit=1).apply(lambda x: my_function(x))
last_valid_data = df_polars[col][0]
df_polars = df_polars.with_columns(
pl.col(col).fill_null(strategy="forward", limit=1).apply(lambda x: my_function(x))
)
Pandas 的期望yields 是:
A B
0 1.0 5.0
1 2.0 NaN
2 2.0 NaN
3 20.0 NaN
4 20.0 NaN
5 20.0 7.0
6 4.0 NaN
7 4.0 9.0
我在北极星上得到的是:
┌──────┬──────┐
│ A ┆ B │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞══════╪══════╡
│ 1 ┆ 5 │
│ 2 ┆ null │
│ 2 ┆ null │
│ null ┆ null │
│ null ┆ null │
│ null ┆ 7 │
│ 4 ┆ null │
│ 4 ┆ 9 │
└──────┴──────┘