Python 当对数据帧中列中不匹配的值求和时,如何强制groupby/sum?
假设我有一个数据帧'df': 数据={'first':['jack','jack','zeke','zeke','zeke'], “last':['sparr'、'sparr'、'smith'、'smith'、'smith'], '方法':['cell','cell','skype','cell','cell'],'duration': [5,5,3,1,1]} 我想对first、last和method的调用持续时间求和。我希望这样,当“方法”不匹配时,它们是“强制求和”,值保留为空 到目前为止,运行一个类似于: df=df.groupby(['first','last','method'],as_index=False).sum() 将回馈:Python 当对数据帧中列中不匹配的值求和时,如何强制groupby/sum?,python,pandas,dataframe,Python,Pandas,Dataframe,假设我有一个数据帧'df': 数据={'first':['jack','jack','zeke','zeke','zeke'], “last':['sparr'、'sparr'、'smith'、'smith'、'smith'], '方法':['cell','cell','skype','cell','cell'],'duration': [5,5,3,1,1]} 我想对first、last和method的调用持续时间求和。我希望这样,当“方法”不匹配时,它们是“强制求和”,值保留为空 到目前为止
first last method duration
jack sparr cell 10
zeke smith skype 3
zeke smith cell 2
但是我要去
first last method duration
jack sparr cell 10
zeke smith 5
我如何修改我的sum语句来实现这一点,或者这在熊猫身上是可能的?谢谢试试这样的方法:
df.groupby(['first', 'last'], as_index=False)[['method', 'duration']]\
.agg({'method':lambda x: x.iloc[0] if x.nunique() == 1 else '',
'duration':'sum'})
输出:
first last method duration
0 jack sparr cell 10
1 zeke smith 5
好的,让我们只按名字和姓氏分组,因为您的总和似乎处于这个级别。对于方法,我们将聚合到一个值,如果方法列中的所有值都相同(nunique==1),否则使用“”为空
我们使用字典来定义每个列的聚合。谢谢!你能解释一下你是如何知道把这些东西连在一起的,以及思维过程是什么吗?这句话太吓人了哈哈:0
first last method duration
0 jack sparr cell 10
1 zeke smith 5