首页 > 解决方案 > Astropy Python 表中的唯一条目

问题描述

我有一个 Astropy 表,

VHzQ_list 

它有 463 个条目,有一个名为“na”的列,其中

np.unique(VHzQ_list['na'])

给出 21 个条目的列表,

ATLAS
CFHQS
DELS
ELAIS 
... 
VIMOS

我想知道 463 中有多少条目是 na='ATLAS'、na=CFHQS 等。对于数据帧,我会这样做:

df.groupby('na').size().sort_values(ascending=False)

VHzQ_list.group_by('na').size().sort_values(ascending=False)

正在扔一个

AttributeError: 'Table' object has no attribute 'size'

错误。什么是 .size() 这里的 Astropy 表?

标签: pythonpandasdataframeuniqueastropy

解决方案


Pythoncollection.Counter是一种在这里得到答案的简单方法:

In [1]: from astropy.table import Table                                                                                                                                                        

In [2]: from collections import Counter                                                                                                                                                        

In [3]: t = Table([['foo', 'bar', 'foo', 'bar', 'foo', 'baz']], names=['a'])                                                                                                                   

In [4]: t                                                                                                                                                                                      
Out[4]: 
<Table length=6>
 a  
str3
----
 foo
 bar
 foo
 bar
 foo
 baz

In [5]: Counter(t['a'])                                                                                                                                                                        
Out[5]: Counter({'foo': 3, 'bar': 2, 'baz': 1})

要使用 Astropy 做到这一点,一种方法是添加一列 1,然后您可以聚合,但这可能不如 pandas 灵活,因为我认为聚合函数必须应用于所有列:

In [23]: t['b'] = 1                                                                                                                                                                            

In [24]: t                                                                                                                                                                                     
Out[24]: 
<Table length=6>
 a     b  
str3 int64
---- -----
 foo     1
 bar     1
 foo     1
 bar     1
 foo     1
 baz     1

In [25]: tg = t.group_by('a')                                                                                                                                                                  

In [26]: tg.groups.aggregate(sum)                                                                                                                                                              
Out[26]: 
<Table length=3>
 a     b  
str3 int64
---- -----
 bar     2
 baz     1
 foo     3

推荐阅读