python - 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 表?
解决方案
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
推荐阅读
- python - 从numpy中的任意维度删除行
- ruby-on-rails - 彪马“提前解雇工人”调查困难重重
- c++ - 为什么一个对象是不可构造的?
- html - 当 HTML/CSS 中需要换行时,用换行符替换字符
- hibernate - Exception java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index, despite using latest version
- python - 如何将电容式土壤湿度传感器 v1.2 的 adc 输出转换为 python(micropython) 中的实际湿度百分比?
- c++ - C++:“数字常量”的数据类型
- ios - 图标 onPress 仅适用于 Android,不适用于 iOS
- c++ - 为什么将 1 添加到“man”后“all_members”变量没有变化?
- iteration - 具有容差系统的 Jacobi 方法