Python 分组操作
我想在熊猫中执行groupby操作。例如,我想将字段B分组如下。 二:任何前面有2的。 三:任何前面有3的。 否则就别管这个牢房 例如: df 结果将是:Python 分组操作,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,我想在熊猫中执行groupby操作。例如,我想将字段B分组如下。 二:任何前面有2的。 三:任何前面有3的。 否则就别管这个牢房 例如: df 结果将是: index A B Count Value (Count: sum by group, Value: average by group) x abc 1-a 1 1 x abc Two 2 3 x xyz Three 2 1 y
index A B Count Value (Count: sum by group, Value: average by group)
x abc 1-a 1 1
x abc Two 2 3
x xyz Three 2 1
y abc 1-b 1 5
y abc 1-c 0 3
y ijk Three 2 1
y ijk Two 1 2
通过使用str.split+agg
为了你的案子
df.groupby(['index','A','B']).agg(lambda x : x.mean() if x.name.startswith('Value') else x.sum()).reset_index()
通过使用str.split+agg
为了你的案子
df.groupby(['index','A','B']).agg(lambda x : x.mean() if x.name.startswith('Value') else x.sum()).reset_index()
也可以使用str.partition:
也可以使用str.partition:
谢谢温家宝!如果我有多个值1、值2、值3,…,代码会是什么样子,。。。。我想知道这些的平均值?还有更方便的方法吗?df.groupby['index','a','B'].aggrembda x:x.mean如果x.name.startswith'Value'else x.sum.reset_index@TylerNGThanks Wen!如果我有多个值1、值2、值3,…,代码会是什么样子,。。。。我想知道这些的平均值?还有更方便的方法吗?df.groupby['index','a','B'].aggrembda x:x.mean如果x.name.startswith'Value'else x.sum.reset_index@TylerNG
df.groupby(['index','A','B']).agg(lambda x : x.mean() if x.name.startswith('Value') else x.sum()).reset_index()
# make new 'B'
df.B.where(df.B.str.contains('1'), other = df.B.str.partition('-')[0], inplace = True)
# group and agg
df.groupby([
'index',
'A',
'B'
]).agg({
'Count' : 'sum',
'Value' : 'mean'
}).reset_index()