简体   繁体   English

在 numpy arrays 中添加项目,其中每个项目都有一个关联的“类型”

[英]Add items in numpy arrays where each item has an associated “type”

I'm wondering if it's possible to add numpy arrays together item-wise, where each item has a "type" associated with it.我想知道是否可以逐项添加numpy arrays ,其中每个项目都有一个与之关联的“类型”。

For example, say I have the following 2 arrays:例如,假设我有以下 2 个 arrays:

array1 = [[2 'x'] [3 'y'] [4 'z']]  
array2 = [[10 'x'] [6 'z']]

And I would like to produce this array:我想生成这个数组:

array3 = [[12 'x'] [3 'y'] [10 'z']]

Is there a straightforward way to do this using numpy ?有没有使用numpy的简单方法来做到这一点? Thanks!谢谢!

You can either use numpy directly or make advantage of pandas built-in groupby method.您可以直接使用 numpy 或利用 pandas 内置 groupby 方法。

Numpy Implementation Numpy 实现

import numpy as np

a1 = np.array([[2, 'x'], [3, 'y'], [4 ,'z']])
a2 = np.array([[10, 'x'] ,[6 ,'z']])

# Stack the two arrays together
a = np.vstack([a1,a2])

# Define "groups"
grp = np.unique(a[:,1])

# Groupby each group in grp and sum the other column
np.array([[a[a[:,1]==g][:,0].astype(float).sum(), g]  for g in grp])
array([['12.0', 'x'],
       ['3.0', 'y'],
       ['10.0', 'z']], dtype='<U32')

Pandas Implementation Pandas 实施

import pandas as pd

# Convert a into a pandas DataFrame
df = pd.DataFrame(a, columns=list('ab'))
# Cast first column type
df['a'] = df['a'].astype(int)

# Use groupby sum
df.groupby('b').sum().reset_index()[['a','b']].to_numpy()
array([[12, 'x'],
       [3, 'y'],
       [10, 'z']], dtype=object)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法重新创建numpy.array,其中每个元素都具有numpy.void类型 - Having trouble recreating an numpy.array where each element has a type of numpy.void 如何计算numpy数组中每个项目的出现次数 - How to calculate occurrence number of each item in numpy arrays 交错两个numpy索引数组,每个数组一个项目 - Interleaving two numpy index arrays, one item from each array 如何构建一个 numpy 数组列表,其中每个数组的大小都是唯一的 - How to build a list of numpy arrays where each array is uniquely sized 列出元组(每个元组包含两个numpy数组) - Making a list of tuples (where each tuple contains two numpy arrays) numpy数组数组的位置 - numpy where for array of arrays 如何将项目添加到numpy数组的每个元组元素? - How to add item to each tuple element of numpy array? 如何返回表格中最受欢迎的项目,但每个项目是唯一的? - How to return most popular items in a table, but where each item is unique? 迭代两个或多个列表/ numpy数组……并相互比较每个项目,并避免python中的循环 - Iterate two or more lists / numpy arrays… and compare each item with each other and avoid loops in python 如何抓取项目的网页,每个项目都有指向新页面的链接 - How to scrape webpage of items, each item has link to new page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM