简体   繁体   English

Python - 如何根据第一列拆分数组?

[英]Python - How to split an array based on the first column?

I have below fake data.我有以下虚假数据。 After reading it into array it will have shape (8, 3).将其读入数组后,它将具有形状 (8, 3)。 Now I want to split the data based on the first column(ID) and return a list of array whose shape will be:[(3,3),(2,3),(3,3)].现在我想根据第一列(ID)拆分数据并返回一个数组列表,其形状为:[(3,3),(2,3),(3,3)]。 I think np.split could do the job by assigning a 1-D array to "indices_or_sections" argument.我认为 np.split 可以通过将一维数组分配给“indices_or_sections”参数来完成这项工作。 But is there any more convenient way to do this?但是有没有更方便的方法来做到这一点?

1   700 35
1   700 35
1   700 35
2   680 25
2   680 25
3   750 40
3   750 40
3   750 40

You can achieve this by using a combination of np.split , sort , np.unique and np.cumsum .您可以通过使用np.splitsortnp.uniquenp.cumsum的组合来实现此目的。

>>> a = [[1, 700, 35],
...      [1, 700, 35],
...      [1, 700, 35],
...      [2, 680, 25],
...      [2, 680, 25],
...      [3, 750, 40],
...      [3, 750, 40],
...      [3, 750, 40]]
>>> a = np.array(a)
>>> # sort the array by first column. 
>>> a = a[a[:,0].argsort()]
>>> np.split(a, np.cumsum(np.unique(a[:, 0], return_counts=True)[1])[:-1])
[array([[  1, 700,  35],
       [  1, 700,  35],
       [  1, 700,  35]]), array([[  2, 680,  25],
       [  2, 680,  25]]), array([[  3, 750,  40],
       [  3, 750,  40],
       [  3, 750,  40]])]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:如何根据第一列中的值将Pandas DataFrame分为子集? - Python: how to split pandas DataFrame into subsets based on the value in the first column? 如何根据列拆分 numpy 数组? - How to split a numpy array based on a column? 根据第一列 Python 3.4.3 中的日期拆分大型 csv 文件 - Split a large csv file based on date in First column Python 3.4.3 使用 Python 根据第一列将 xlsx 文件拆分为其他 xlsx 文件 - Split xlsx file into other xlsx files based on first column with Python 如何根据python中的空格将一列拆分为4列? - How to split a column into 4 columns based on spaces in python? 在Python / numpy中,如何根据数组的第一列(即索引)解散/拆分数组? - In Python / numpy, how do I unravel / split an array according to its first column, which is an index? 如何根据第一列的内容拆分一个巨大的 csv 文件? - How to split a huge csv file based on content of first column? python:如何拆分按第一列分组的Excel文件 - python: how to split excel files grouped by first column 如何使用python根据一列将整个数据集分为4个范围 - How to split the whole dataset into 4 range based on one column using python Python - 如何基于分米计将列中的单元格拆分为新行 - Python - How to split cell in a column to a new row based of a delmimeter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM