[英]Grouping columns from data by same value in first column
So I'm trying to figure out a way to group up all the rows in data that have the same value in the first column. 因此,我试图找出一种对第一列中具有相同值的数据中的所有行进行分组的方法。
So say I have: 所以说我有:
col 1: col 2:
0 3
0 4
0 5
1 9
1 10
2 7
I want to use either some basic python or numpy to read that data from col 1 and find all the ones that have 0 and group that row up together in a list or something, and then all the ones that have a 1 in col1, etc. . 我想使用一些基本的python或numpy来从col 1中读取该数据,并找到所有具有0的数据并将它们分组在列表中或某物中,然后将所有在col1中具有1的数据分组,等等。 。 etc. .. I was able to figure this out if the numbers just increase by 1 in col 1, but my inputs have have any sort of float so that isn't reliable. 等等..我能够弄清楚,如果数字只是在第1列中增加1,但是我的输入内容有任何类型的浮点数,因此并不可靠。
I've used this in the past, when trying to avoid using a mask with for u in np.unique
or going to pandas or itertools.groupby
: 过去,在尝试避免for u in np.unique
使用带遮罩的模板时for u in np.unique
或for u in np.unique
pandas或itertools.groupby
时,我都使用了它:
np.split(col2, np.where(np.diff(col1))[0]+1)
Works for floats in col1
: 适用于col1
float:
col1 = np.sort(np.repeat(np.random.rand(4), np.random.randint(2,4,4)))
col2 = np.arange(len(col1))
col1
#array([ 0.39855008, 0.39855008, 0.84331316, 0.84331316, 0.94124952,
# 0.94124952, 0.94124952, 0.9480605 , 0.9480605 , 0.9480605 ])
np.split(col2, np.where(np.diff(col1))[0]+1)
#[array([0, 1]), array([2, 3]), array([4, 5, 6]), array([7, 8, 9])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.