Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用np.where()对象创建列表列表_Python_Python 3.x_Pandas_List_Numpy - Fatal编程技术网

Python 使用np.where()对象创建列表列表

Python 使用np.where()对象创建列表列表,python,python-3.x,pandas,list,numpy,Python,Python 3.x,Pandas,List,Numpy,我试图用Python创建一个列表列表,方法是使用np.where(pd.isnull(x))创建要追加的列表。本质上,我试图做的是循环遍历data.frame,为每一行查找哪些值不是null。我之所以使用np.where(),是因为我希望将非空值的索引作为内部列表,然后将其附加到外部列表。然后,此外部列表将仅缩减为唯一值。我目前的想法大致如下: outer_list = [] outer_list.append(list(range(0, number_of_columns)) #This is

我试图用Python创建一个列表列表,方法是使用
np.where(pd.isnull(x))
创建要追加的列表。本质上,我试图做的是循环遍历data.frame,为每一行查找哪些值不是null。我之所以使用
np.where()
,是因为我希望将非空值的索引作为内部列表,然后将其附加到外部列表。然后,此外部列表将仅缩减为唯一值。我目前的想法大致如下:

outer_list = []
outer_list.append(list(range(0, number_of_columns)) #This is the longest possible return,
#but it may not be found in the data frame
for i in list(range(0, len(data_frame.index))):
       row = data_frame.iloc[i,:].tolist()
       item = np.where(pd.notnull(row))[0] #using [0] to turn the array into a list 
       outer_list.append(item)
unique_list = np.unique(outer_list)
但是,当我尝试此
项时
会还原回数组(?)对象,例如追加时
数组([5,6,7,8],dtype=int64)
,这是我不想要的。
外部列表
必须包含一系列列表。我怎样才能避免这个/我应该怎样做

我确信这不是解决这个问题的最佳方法,因此任何关于如何改进的建议都将非常感谢,我对Python非常陌生

数据如下所示:

我不知道如何最好地做一张桌子

与上面一样,代码将获取非空值的索引并生成列表列表,从最长的列表开始(将添加到循环之外)

然后浏览表中的行,分别为每行添加以下列表:

[0,1,2,3]
[1,2,3,4]
[2,3,4]
[0,1,2,3]
这将全部附加到
外部列表
,以给出以下结果:

[[0,1,2,3,4], [0,1,2,3], [1,2,3,4], [2,3,4], [0,1,2,3]]
然后将其缩减为一个唯一的列表:

[[0,1,2,3,4], [0,1,2,3], [1,2,3,4], [2,3,4]] 

因为元素1和4是相同的。

您能显示您的示例数据和预期输出吗?仅使用本机pandas函数可能更简单。
np。其中
返回数组的元组,每个维度一个数组
np.where(cond)[0]
仅从元组中提取数组
np.where(cond)[0].tolist()
将数组转换为列表。但我不确定这对
np.unique
步骤是否有帮助。@hpaulj这完全符合我的要求。非常感谢。
[[0,1,2,3,4], [0,1,2,3], [1,2,3,4], [2,3,4]]