python - 如何在元素中考虑 NaN 将一维数组转换为 nd 数组?
问题描述
我有一个如下列表,我想根据当前值中的 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
推荐阅读
- json - Is there any way to get JsonProvider to parse this as an array of items, rather than a named list?
- javascript - 组件销毁后侦听器仍处于活动状态
- jenkins-plugins - Jenkins Xvfb 插件 - 选择不正确的 -fbdir 名称
- android - Cannot connect to the API using Volley
- java - 我可以在两个活动中使用相同的方法吗?
- python - 在 Pandas 中按 ID 有条件地删除行
- frequency - 在时间序列数据中应用巴特沃斯过滤器
- sse - SSE 比较返回 NAN 向量
- excel - 我需要为唯一输出创建一个循环,将其复制到同一个工作表中的不同列
- docker - Docker-Compose,从当前文件夹的 2 级下发出安装卷