gpt4 book ai didi

python - 如何将填充应用于1?

转载 作者:行者123 更新时间:2023-12-01 01:44:38 25 4
gpt4 key购买 nike

我有一个如下所示的数据框,

   A  B  C  D
0 1 0 0 0
1 0 1 0 0
2 0 1 0 0
3 0 0 1 0

我想把它转换成这样,

   A  B  C  D
0 1 0 0 0
1 1 1 0 0
2 1 1 0 0
3 1 1 1 0

到目前为止我已经尝试过,

df= df.replace('0',np.NaN)
df=df.fillna(method='ffill').fillna('0')

我的上面的代码工作正常,

但我认为还有其他更好的方法来解决这个问题,

最佳答案

使用cumsum将数据转换为数字,然后替换为 DataFrame.mask :

df = df.mask(df.astype(int).cumsum() >= 1, '1')
print (df)
A B C D
0 1 0 0 0
1 1 1 0 0
2 1 1 0 0
3 1 1 1 0

详细信息:

print (df.astype(int).cumsum())
A B C D
0 1 0 0 0
1 1 1 0 0
2 1 2 0 0
3 1 2 1 0

或者在numpy中使用numpy.where相同的原理:

arr = df.values.astype(int)

df = pd.DataFrame(np.where(np.cumsum(arr, axis=0) >= 1, '1', '0'),
index=df.index,
columns= df.columns)
print (df)
A B C D
0 1 0 0 0
1 1 1 0 0
2 1 1 0 0
3 1 1 1 0

关于python - 如何将填充应用于1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51513050/

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