Pandas groupby where all columns are added to a list prefixed by column name
<p>I have a CSV file that looks like this:</p>

<pre><code>id1,feat1,feat2,feat3
a,b,asd,asg
c,d,dg,ag
a,e,sdg,as
c,f,as,sdg
c,g,adg,sd
</code></pre>

<p>I read it in  to a dataframe with <code>df = pd.read_csv("file.csv")</code>.</p>

<p>I would like group by <code>id1</code> and combine all the other columns in one line in  the group with the header name added as a prefix. That is the output should be a data frame that looks like:</p>

<pre><code>a [feat1=b,feat1=e,feat2=asd,feat2=sdg,feat3=asg,feat3=as]
c [feat1=d,feat1=f,feat1=g,feat2=dg,feat2=as,feat2=adg,feat3=ag,feat3=sdg,feat3=sd]
</code></pre>

<p><code>df.groupby('id1')</code> will start me off but I am not sure where to go from there.</p>

<p>What is a good way to do this?</p>

<p>Applying this function will work:</p>

<pre><code>def func(dfg):
    dfu = dfg.unstack()
    result = dfu.index.get_level_values(0) + '=' + dfu.values
    return result.tolist()

df.groupby('id1').apply(func)
</code></pre>

<hr>

<p><strong>Explanation</strong>: let's consider one group, for instance <code>dfg = df[df['id1'] == 'c']</code>.</p>

<pre><code>dfg.unstack()
Out[35]: 
id1    1      c
       3      c
       4      c
feat1  1      d
       3      f
       4      g
feat2  1     dg
       3     as
       4    adg
feat3  1     ag
       3    sdg
       4     sd
</code></pre>

<p>By unstacking you get the values aligned with the column names (ignore the index values in between). All you need to do is concatenate:</p>

<pre><code>dfu.index.get_level_values(0) + '=' + dfu.values
Out[36]: 
Index(['feat1=d', 'feat1=f', 'feat1=g', 'feat2=dg', 'feat2=as', 'feat2=adg',
       'feat3=ag', 'feat3=sdg', 'feat3=sd'],
      dtype='object')
</code></pre>

<p>Finally, convert to list before returning, otherwise you end up with index objects. </p>

python pandas