我想通过仅替换数据框中连续的 0 来清理一些数据
给定:
import pandas as pd
import numpy as np
d = [[1,np.NaN,3,4],[2,0,0,np.NaN],[3,np.NaN,0,0],[4,np.NaN,0,0]]
df = pd.DataFrame(d, columns=['a', 'b', 'c', 'd'])
df
a b c d
0 1 NaN 3 4.0
1 2 0.0 0 NaN
2 3 NaN 0 0.0
3 4 NaN 0 0.0
期望的结果应该是:
a b c d
0 1 NaN 3 4.0
1 2 0.0 NaN NaN
2 3 NaN NaN NaN
3 4 NaN NaN NaN
其中 c 列和 d 列受到影响,但 b 列不受影响,因为它只有 1 个零(而不是连续的 0)。
我已经尝试过这个答案: Replacing more than n consecutive values in Pandas DataFrame column
这是正确的,但解决方案将第一个 0 保留在给定列中,这在我的情况下是不需要的。
最佳答案
让我们用mask
做shift
df=df.mask((df.shift().eq(df)|df.eq(df.shift(-1)))&(df==0))
Out[469]:
a b c d
0 1 NaN 3.0 4.0
1 2 0.0 NaN NaN
2 3 NaN NaN NaN
3 4 NaN NaN NaN
关于pandas - 在 Pandas 中用 NaN 替换连续的 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61752420/