## Numpy：如何通过用零填充空元素来修正不同长度行的数组？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (401)

```data = np.array([[1, 2, 3, 4],
[2, 3, 1],
[5, 5, 5, 5],
[1, 1]])

result = fix(data)
print result

[[ 1.  2.  3.  4.]
[ 2.  3.  1.  0.]
[ 5.  5.  5.  5.]
[ 1.  1.  0.  0.]]```

### 2 个回答

```def numpy_fillna(data):
# Get lengths of each row of data
lens = np.array([len(i) for i in data])

# Mask of valid places in each row

# Setup output array and put elements from data into masked positions
return out```

```In [222]: # Input object dtype array
...: data = np.array([[1, 2, 3, 4],
...:                  [2, 3, 1],
...:                  [5, 5, 5, 5, 8 ,9 ,5],
...:                  [1, 1]])

In [223]: numpy_fillna(data)
Out[223]:
array([[1, 2, 3, 4, 0, 0, 0],
[2, 3, 1, 0, 0, 0, 0],
[5, 5, 5, 5, 8, 9, 5],
[1, 1, 0, 0, 0, 0, 0]], dtype=object)```

pandas如下：

```In [1]: import pandas as pd

In [2]: df = pd.DataFrame([[1, 2, 3, 4],
...:                    [2, 3, 1],
...:                    [5, 5, 5, 5],
...:                    [1, 1]], dtype=float)

In [3]: df.fillna(0.0).values
Out[3]:
array([[ 1.,  2.,  3.,  4.],
[ 2.,  3.,  1.,  0.],
[ 5.,  5.,  5.,  5.],
[ 1.,  1.,  0.,  0.]])```