3 回答

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超9個(gè)贊
如果可以使用pandas,replace則將在一條指令中顯式顯示替換項(xiàng):
import pandas as pd
import numpy as np
a = np.array([[1, 1, 1, 1, 1, 0, 1, 0, 0, 2, 1],
[2, 1, 0, 0, 0, 1, 2, 1, 1, 2, 2]])
df = pd.DataFrame(a, dtype=np.float64)
df.replace(0, method='pad', axis=1)

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
我的版本基于逐步滾動(dòng)和初始數(shù)組的屏蔽,不需要其他庫(kù)(numpy除外):
import numpy as np
a = np.array([[1, 1, 1, 1, 1, 0, 1, 0, 0, 2, 1],
[2, 1, 0, 0, 0, 1, 2, 1, 1, 2, 2]])
for i in xrange(a.shape[1]):
a[a == 0] = np.roll(a,i)[a == 0]
if not (a == 0).any(): # when all of zeros
break # are filled
print a
## [[1 1 1 1 1 1 1 1 1 2 1]
## [2 1 1 1 1 1 2 1 1 2 2]]
添加回答
舉報(bào)