gpt4 book ai didi

python - 用 `ffill`(或任何其他方法)填充 na 值,并递增 1

转载 作者:行者123 更新时间:2023-11-28 22:10:29 25 4
gpt4 key购买 nike

我有以下 DF,我想填充 NA 值。

我想用递增的值填充它,如下所示:

import pandas as pd

data = [[1,1 ],[1, 1 ], [2, None], [3, None]]

df = pd.DataFrame(data, columns = ['user', 'days_unseen'])

#current behavior of ffill, leaves value the same
df['value']=df['value'].ffill()
print(df)

#desired fill - increments last value by 1
desired_data = [[1,1 ],[1, 1 ], [2, 2], [3, 3]]
desired_df = pd.DataFrame(desired_data, columns = ['user', 'days_unseen'])
print(desired_df)

最佳答案

链条Series.isnaSeries.cumsum用于计数缺失值并通过前向填充缺失值来添加最后一个非缺失值:

df['value'] = df['days_unseen'].isna().cumsum() + df['days_unseen'].ffill()
print(df)
user days_unseen value
0 1 1.0 1.0
1 1 1.0 1.0
2 2 NaN 2.0
3 3 NaN 3.0

关于python - 用 `ffill`(或任何其他方法)填充 na 值,并递增 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56617701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com