按熊猫中列值的子字符串分组

在对pandas数据框进行分组时,我发现数据中的问题不能有效地对数据框进行分组,现在我的分组看起来像-

challenge                      count    mean
['acsc1','[object Object]']    1   0.000000
['acsc1','undefined']          1   0.000000
['acsc1','wind-for']          99   379.284146
['acsc1']                      47   19.340045
['acsc10','wind-for']         73   370.148354
['acsc10']                     22   143.580856

如何将以ascs1开头的这些行分组为一行(将其他列的值相加),并将acsc10分组为一行,依此类推?所需的结果应类似于-

challenge       category       count    mean
acsc1           wind-for       148      398.62
acsc10          wind-for        95      513.72

但是我知道类别列可能有点杂乱无章。

ferfrevervr 回答:按熊猫中列值的子字符串分组

我们可以做到

s=pd.DataFrame(df['challenge'].tolist(),index=df.index,columns=['challenge','cate'])
d={'cate':'last','count':'count','mean':'sum'}
df=pd.concat([df.drop('challenge',1),s],axis=1).\
    groupby('challenge').agg(d).reset_index()

更新修复字符串类型列表

import ast
df.challenge=df.challenge.apply(ast.literal_eval)
df.groupby(df.challenge.str[0]).sum()
           count        mean
challenge                   
acsc1        148  398.624191
acsc10        95  513.729210
,

这应该使您获得最初请求的结果(没有类别列) df.groupby(df.challenge.apply(lambda x: x.split(",")[0].strip("[']"))).sum().reset_index()

输出

challenge   count   mean
0   acsc1   148     398.624191
1   acsc10  95      513.729210
本文链接:https://www.f2er.com/3113352.html

大家都在问