Python 通过在数组列中应用np.maximum.reduce进行分组
我需要对数据帧进行分组,将np.maximum.reduce(使用每个位置的最大值创建一个新数组)应用于包含numpy数组的列 例如:Python 通过在数组列中应用np.maximum.reduce进行分组,python,pandas,numpy,pandas-groupby,Python,Pandas,Numpy,Pandas Groupby,我需要对数据帧进行分组,将np.maximum.reduce(使用每个位置的最大值创建一个新数组)应用于包含numpy数组的列 例如: import pandas as pd import numpy as np df = pd.DataFrame([{'name': 'John', 'points' : [1,1,3,5]},{'name': 'John', 'points' : [2,0,1,5]},{'name': 'John', 'points' : [4,1,2,2]}]) df['
import pandas as pd
import numpy as np
df = pd.DataFrame([{'name': 'John', 'points' : [1,1,3,5]},{'name': 'John', 'points' : [2,0,1,5]},{'name': 'John', 'points' : [4,1,2,2]}])
df['points'] = df['points'].apply(lambda x : np.array(x)) # converting the list column to pd.array()
df
name points
0 John [1, 1, 3, 5]
1 John [2, 0, 1, 5]
2 John [4, 1, 2, 2]
如果我尝试使用apply(np.max),我会得到以下错误:
result = df.groupby(['name'])['points'].apply(np.maximum.reduce).reset_index()
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
分组后的预期结果:
name points
0 John [4, 1, 3, 5]
如果我尝试使用np.sum(),groupby可以正常工作:
result = df.groupby(['name'])['points'].apply(np.sum).reset_index()
result
name points
0 John [7, 2, 6, 12]
但我需要应用np.max.reduce函数:
a = np.array([1,1,3,5])
b = np.array([2,0,1,5])
c = np.array([4,1,2,2])
test = np.maximum.reduce([a,b,c])
test
array([4, 1, 3, 5])
使用数组的numpy效率实现此groupby(类似于maximum.reduce)的解决方法是什么?如果要使用
np.maximum.reduce
,请首先对分组值应用list
df.groupby('name')['points'].apply(lambda x: np.maximum.reduce(list(x)))
替代方法:让我们尝试使用
np.stack
和np.max
df.groupby('name')['points'].apply(lambda x: np.stack(x).max(0))
如果要使用
np.maximum.reduce
则首先对分组值应用list
df.groupby('name')['points'].apply(lambda x: np.maximum.reduce(list(x)))
替代方法:让我们尝试使用
np.stack
和np.max
df.groupby('name')['points'].apply(lambda x: np.stack(x).max(0))
更新了我的答案,使用了
np.maximum.reduce
和另一种方法。如果不了解更多关于这个问题的信息,很难说,但是可能值得将点列分为四个不同的列?使用np.maximum.reduce
更新了我的答案,并使用了另一种方法。如果不了解更多关于这个问题的信息,很难说,但可能值得将点列分为四个不同的列?效果很好!非常感谢你!(我以为我以前试过这个,显然我没有。哈哈)很高兴随时帮忙,效果很好!非常感谢你!(我以为我以前试过这个,显然我没有。哈哈)很乐意随时帮忙