Skip to main content
 首页 » 编程设计

Python pandas 系列按索引 : Data must be 1 dimensional error 访问

2024年10月24日12jillzhang

我有一个 pandas 系列(名为“clusters”),有点像:

0 [[1, 2, 3], [4, 5, 6]] 
1 [[1, 2, 3], [9, 10, 11]] 

我通过转换得到这个系列:list > dataframe > as_matrix 处理矩阵后,我得到了系列。

我想通过此处为 0 和 1 的索引访问该系列。 但是当我做 clusters[0] 或 clusters[1] 时。

我得到一个错误Data must be 1 dimensional error

我不知道这里有什么问题。

或者,如果循环遍历这个系列,我该如何访问索引? 所以如果我说:

for k in clusters: 
      print k 

我得到 [[1, 2, 3], [4, 5, 6]]。但我想获取此“[[1, 2, 3], [4, 5, 6]]” 链接到的索引。我怎么得到那个。我尝试了 k.index 但没有任何效果。

请您参考如下方法:

您可以遍历项目,它使用索引标签进行迭代:

In [11]: for ind, k in clusters.items(): 
             print(ind) 
0 
1 

我认为您的系列有些奇怪,因为您应该能够通过索引访问:

In [12]: clusters[0] 
Out[12]: [[1, 2, 3], [4, 5, 6]] 
 
In [13]: clusters.loc[0] 
Out[13]: [[1, 2, 3], [4, 5, 6]]