gpt4 book ai didi

python - 是否有一个函数(或更好的方法)使用 Pandas 中具有相似值的两列来聚合计数值的数量?

转载 作者:行者123 更新时间:2023-12-01 00:24:45 25 4
gpt4 key购买 nike

如图所示,

  • 其中两列具有相同类型的数据。
  • Type1 是 Pokemon 的主要类型,type2 是 Pokemon 的次要类型。
  • 相同类型如地面可以出现在类型1中列以及typ2列
  • 例如,第一行groundtype1,但对于第二行和第三行地面type2

现在,我想做的是获取所有具有相同类型的神奇宝贝无论是type1还是type2,例如,这里地面数为5,毒药数为4,依此类推(即使类型 2 中出现 4 个接地,类型 1 中出现 1 个接地)

dataset

type2_count = {}
type_count = {}
for i in type1:
type_count[i]=type_count.get(i,0)+1
for i in type2:
type_count[i]=type_count.get(i,0)+1
print(type_count)

我期望每种类型的神奇宝贝的数量(无论类型 1 或类型 2)

最佳答案

IIUC,你可以使用

# with numpy
type_counts = np.hstack(df[['type1', 'type2']].values)
type_counts = dict(zip(*np.unique(type_counts , return_counts=True)))
print(type_counts)

# using pandas
print(df['type1'].append(df['type2']).value_counts().to_dict())

{'ground': 5, 'poison': 5, ....}

关于python - 是否有一个函数(或更好的方法)使用 Pandas 中具有相似值的两列来聚合计数值的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58682678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com