有没有办法从 python 中的元组列表中获取丰度数据

is there a way of getting abundance data out of a list of tuples in python

我有一个看起来像这样的数据集:

Species = [(30, "cat"), (30, "dog"), (30, "bird"), (45, "cat"), (45, "dog"), (60, "bird"), (70, "lizard"), (70, "frog")]

我想做的是计算每个位置的物种数量,这样我就可以 运行 进行回归。 所以我想我需要我的输出是这样的

location = (30,45,60,70)
species_num = (3,2,1,2)

有谁知道我应该从哪里开始?我已经为此工作了几个小时,但每次我认为我快要接近它时,它都不起作用。

使用 numpy 或 pandas

的解决方案

numpy.unique(return_counts=True) 正是您要找的地址。数字分量由 list(zip(*Species))[0].

提取
import numpy as np
location, species_num = np.unique(list(zip(*Species))[0], return_counts=True)

或者,pandas.DataFrame.groupby().size()

import pandas as pd
sr = pd.DataFrame(Species, columns=["location", "animal"])\
       .groupby("location").size()
location = sr.index.values
species_num = sr.values

输出

print(location)
Out[136]: array([30, 45, 60, 70])

print(species_num)
Out[137]: array([3, 2, 1, 2])

您可以使用python计数器来计算values.Try这个

from collections import Counter
count = [i[0] for i in Species]
counter = Counter(count)
values = counter.values()
keys = counter.keys()

输出

counter.values()
dict_values([3, 2, 1, 2])

counter.keys()
dict_keys([30, 45, 60, 70])

使用 Collections 模块中的 Counter,它将 return 一个字典,其中键是数字,值是出现次数。

from collections import Counter
counter = Counter(sp[0] for sp in Species) 
>>> counter
   Counter({30: 3, 45: 2, 60: 1, 70: 2})

collections 模块中的计数器为唯一元素创建字典并在可迭代对象中对它进行计数。

   from collections import Counter
   my_list = [field[0] for field in Species]

   count = Counter(my_list)
   count