python - 有没有一些优雅的方法来操纵我的 ndarray

标签 python numpy multidimensional-array

我有一个名为xs的矩阵:

array([[1, 1, 1, 1, 1, 0, 1, 0, 0, 2, 1],
       [2, 1, 0, 0, 0, 1, 2, 1, 1, 2, 2]])

现在我想用同一行中最近的前一个元素替换零(假设第一列必须非零。)。 粗略的解决方案如下:

In [55]: row, col = xs.shape

In [56]: for r in xrange(row):
   ....:     for c in xrange(col):
   ....:         if xs[r, c] == 0:
   ....:             xs[r, c] = xs[r, c-1]
   ....: 

In [57]: xs
Out[57]: 
array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1],
       [2, 1, 1, 1, 1, 1, 2, 1, 1, 2, 2]])

任何帮助将不胜感激。

最佳答案

如果可以使用pandas , replace将在一条指令中明确显示替换:

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)

关于python - 有没有一些优雅的方法来操纵我的 ndarray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17164004/

相关文章:

python - 如何确定 SelectFromModel() 中用于选择特征的阈值?

python - 高效计算 numpy/scipy 中的交换矩阵

Android ArrayList 到多维 ArrayList

java - 如何打印彼此相邻的二维数组矩阵的格式化字符串

python - 从 shell 脚本执行 python 脚本(有参数)

python - Excel 列中数字更改的次数

python - 如何从 CMake 获取 "install"Python 代码?

python - 为什么包络曲线一开始就是错误的?

python - 比较同一数据框列中的值

c++ - 如何仅将矩阵的一维分配给 C++ 中的简单数组