如何将多列分组为逗号分隔的输出

时间:2019-03-20 09:58:03

标签: pandas

我有以下数据框

import pandas as pd
d= {
    'ID':[1,2,3,4,5],
    'Fruit':['Jack','Apple','Guava','Orange','Apple],
    'Market':['k','r','r','t','r]
}
df= pd.DataFrame(data=d)
df

对于分组水果和市场,以下是代码

df.groupby('Fruit')['Market'].value_counts().reset_index(name='Count')

但是如何获得以下输出?

Market  Fruit1 Fruit2   Count   Individual-Count1  Individual-Count2
r       Apple   Guava   3        2                 1
k       Jack            1         1
t       Orange          1         1

在Fruit1,Fruit2上应该只有唯一值。

i.e对市场和水果进行分组,并在“计数”列中进行计数,在“水果”中将单个计数作为新列中的逗号分隔值。

1 个答案:

答案 0 :(得分:2)

我认为您需要:

f = lambda x: ','.join(x.value_counts().astype(str))
d = {'Market':'count', 'ID':'Individual-Count'}

df1 = (df.groupby('Market')
        .agg({'Fruit':','.join, 'Market':'size', 'ID':f})
        .rename(columns=d)
        .reset_index())

print (df1)
  Market        Fruit  count Individual-Count
0      k         Jack      1                1
1      r  Apple,Guava      2              1,1
2      t       Orange      1                1

编辑:

def f(x):
    v = x['Fruit'].value_counts()
    a = pd.Series(v.index)
    b = pd.Series(v.values)
    return pd.DataFrame({'Fruit':a, 'Individual-Count':b})

df1 = df.groupby('Market').apply(f).unstack()
df1.columns = [f'{a}{b+1}' for a, b in df1.columns]

df1['count'] = df1.index.map(df['Market'].value_counts().get)
df1 = df1.reset_index()
print (df1)
  Market  Fruit1 Fruit2  Individual-Count1  Individual-Count2  count
0      k    Jack    NaN                1.0                NaN      1
1      r   Apple  Guava                2.0                1.0      3
2      t  Orange    NaN                1.0                NaN      1

编辑:

def f(x):
    v = x['Fruit'].value_counts()
    return pd.Series({'Fruit':', '.join(v.index), 
                      'Individual-Count':','.join(v.astype(str).values)})

df1 = df.groupby('Market').apply(f)
df1['count'] = df1.index.map(df['Market'].value_counts().get)
df1 = df1.reset_index()
print (df1)
  Market         Fruit Individual-Count  count
0      k          Jack                1      1
1      r  Apple, Guava              2,1      3
2      t        Orange                1      1