聚合分组索引中拆分字符串的值

sna*_*ack 3 python pandas

我有一个看起来像这样的数据框:

index  name     value
1      Foo      9
2      Bar      11
3      Foo      2
4      Bar      4
5      Foo,Bar  3
Run Code Online (Sandbox Code Playgroud)

如果df.groupby('name').count()我知道了:

         value
name
Foo      2
Bar      2
Foo,Bar  1
Run Code Online (Sandbox Code Playgroud)

我想拆分Foo,Bar并在结果元组中存在的索引中的每个值加1,以使分组的数据框看起来像:

         value
name
Foo      3
Bar      3
Run Code Online (Sandbox Code Playgroud)

我可以想到使用for循环执行此操作的方法,但我想知道是否存在一些内置的熊猫方法来解决此类问题。

jez*_*ael 6

对于大熊猫0.25+使用Series.str.splitSeries.explodeflatten Series,那么对于数Series.value_countsSeries.to_frame

df1 = df['name'].str.split(',').explode().value_counts().to_frame('value')
print (df1)
     value
Foo      3
Bar      3
Run Code Online (Sandbox Code Playgroud)

对于另一个版本使用splitexpand=True用于DataFrameDataFrame.stackflatten Series

df1 = df['name'].str.split(',', expand=True).stack().value_counts().to_frame('value')
print (df1)
     value
Foo      3
Bar      3
Run Code Online (Sandbox Code Playgroud)