Astropy表操作:如何创建一个新表,其中行按列中的值分组?

问题描述 投票:1回答:2

我有一个包含多行和多列的表。其中一列具有不同的数字,可重复多次。如何创建一个新的astropy表,它只存储具有重复数量超过3次的列的行?

例:

enter image description here

请注意,0129在c列中重复3次,2780次在c列中重复4次。我想我的代码然后创建新表:

修改过的表

enter image description here

我正在使用astropy模块,具体而言:

from astropy.table import Table

我假设我需要使用for循环来完成此任务并最终完成命令

new_table.add_row(table[index]) 

大局,我想要完成的是:

if column_c_value repeats >=3:
    new_table.add_row(table[index])

谢谢您的帮助!我有点被困在这里,非常感谢洞察力。

python tabular astropy
2个回答
1
投票

您可以使用Table grouping功能:

In [2]: t = Table([[1, 2, 3, 4, 5, 6, 7, 8],
   ...:            [10, 11, 10, 10, 11, 12, 13, 12]],
   ...:            names=['a', 'id'])

In [3]: tg = t.group_by('id')

In [4]: tg.groups
Out[4]: <TableGroups indices=[0 3 5 7 8]>

In [6]: tg.groups.keys
Out[6]: 
<Table length=4>
  id 
int64
-----
   10
   11
   12
   13

In [7]: np.diff(tg.groups.indices)
Out[7]: array([3, 2, 2, 1])

In [8]: tg
Out[8]: 
<Table length=8>
  a     id 
int64 int64
----- -----
    1    10
    3    10
    4    10
    2    11
    5    11
    6    12
    8    12
    7    13

In [9]: ok = np.zeros(len(tg), dtype=bool)

In [10]: for i0, i1 in zip(tg.groups.indices[:-1], tg.groups.indices[1:]):
    ...:     if (i1 - i0) >= 3:
    ...:         ok[i0:i1] = True
    ...: tg3 = tg[ok]
    ...: tg3
    ...: 
Out[10]: 
<Table length=3>
  a     id 
int64 int64
----- -----
    1    10
    3    10
    4    10

In [12]: for tgg in tg.groups:
    ...:     if len(tgg) >= 2:
    ...:         print(tgg)  # or do something with it
    ...:         
 a   id
--- ---
  1  10
  3  10
  4  10
 a   id
--- ---
  2  11
  5  11
 a   id
--- ---
  6  12
  8  12

0
投票

我提出了一个解决方案,使用比@TomAldcroft's解决方案更少的花哨工具,并实际过滤掉短群。让我们假设具有重复元素的列在'id'解决方案中称为@TomAldcroft's。然后,

from collections import Counter
import numpy as np
min_repeats = 3 # Let's say selected rows must have 'id' repeated at least 3 times

cntr = Counter(t['id'])
repeated_elements = [k for k, v in cntr.items() if v >= min_repeats]
mask = np.in1d(t['id'], repeated_elements)
new_table = t[mask]
© www.soinside.com 2019 - 2024. All rights reserved.