python - 如何在考虑元素中的 NaN 的情况下将一维数组转换为 n 维数组?

标签 python

我有一个如下所示的列表,我想根据存在的值中的 NaN 将这些元素分解为 n 维。

输入:

[nan 0.1 0.4 0.6 nan 0.8 0.7 0.9 nan 0.3 0.6 0.8]

输出:

[[0.1 0.4 0.6]
 [0.8 0.7 0.9]
 [0.3 0.6 0.8]]

如何实现这一目标,

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

l=[nan 0.1 0.4 0.6 nan 0.8 0.7 0.9 nan 0.3 0.6 0.8]

m_l=[]
t=[]
for val in l:
    if np.isnan(val):
        if len(t)==0:
            continue
        m_l.append(t)
        t=[]
    else:

        t.append(val)
m_l.append(t)

但我正在寻找改进的解决方案。

最佳答案

假设您想要一个平方数组,因此每行都有相同数量的项目:

l=[np.NaN, 0.1, 0.4, 0.6, np.NaN, 0.8, 0.7, 0.9, np.NaN, 0.3, 0.6, 0.8]
m_l2 = np.array(l).reshape((np.isnan(l).sum(),-1))[:,1:]

将输出:

array([[0.1, 0.4, 0.6],
   [0.8, 0.7, 0.9],
   [0.3, 0.6, 0.8]])

分解代码:

m_l2 = np.array(l) #Convert it to a np array from list
nan_count = np.isnan(l).sum() #Counting the amount of NaN in the array
m_l2 = m_l2.reshape((nan_count,-1)) #Reshaping it according to the amoun of NaNs as rows, with auto infering column count
m_l2 = m_l2[:,1:] #Removing the first column, which is all NaNs

关于python - 如何在考虑元素中的 NaN 的情况下将一维数组转换为 n 维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53390635/

相关文章:

python - 导入错误: No module named tastypie. API

python - 将文件复制到另一个文件夹时缺少文件

python - 将查找表应用于 DataFrame 以获取 bin 或范围

python - 如何使用 Python 启动应用程序

python - 函数内列表的各个元素

python - Bokeh 数据表宽度

Python pandas dataframe 获取列值的所有组合?

python - 从 werkzeug 导入安全导入 werkzeug VS

python - 在 Python 中为数据创建直方图

python - 在 Python 中从文件名中提取子字符串?