0

Create Sample Data

import pandas
from pandas import DataFrame
data = [["2018-03-01","2018-03-01","2018-05-01","2018-05-01","2018-06-03"],[20,30,40,10,70],
    ["2017-12-01","2017-12-01","2017-12-05","2017-12-06","2017-12-21"]]   

sample_df = DataFrame.from_records(data).transpose()
sample_df

Sample Data

        0        1     2
0   2018-03-01  20  2017-12-01
1   2018-03-01  30  2017-12-01
2   2018-05-01  40  2017-12-05
3   2018-05-01  10  2017-12-06
4   2018-06-03  70  2017-12-21

Need to create something like below after grouping on column "0" and creating a list of values in column 2 and column 3

   0          1           2
2018-03-01  [20,30]  [2017-12-01,2017-12-01]
2018-05-01  [40,10]  [2017-12-05,2017-12-06]
2018-06-03  [70]     [2017-12-21]

Tried using apply and lambda functions but it didn't work out.

Any suggestions.

Vijay Dahiya
  • 138
  • 7
  • `sample_df.groupby(0).agg(list)` as another alt. – cs95 Apr 24 '19 at 22:32
  • What @cs95 says. If you have more columns, but only want to specifically aggregate certain, use the following: `sample_df.groupby(0).agg({1:list, 2:list})` – Erfan Apr 24 '19 at 22:34
  • @Erfan Funny, but the solution in my comment was not explicitly stated in any of the answers to that question. So I thought I'd add one [here](https://stackoverflow.com/a/55839464/4909087). – cs95 Apr 24 '19 at 22:38
  • Funny, never noticed either. You should actually add the example of multiple columns as well. Pretty sure many beginners find that useful @cs95 – Erfan Apr 24 '19 at 22:45
  • @Erfan Nice suggestion, thanks! I've added it in. – cs95 Apr 24 '19 at 22:50
  • @cs95 it is rare to see, agg and unnest questions close to each others https://stackoverflow.com/questions/55839411/flatten-dataframe-cell-items-from-arrays-to-multiple-rows :-) – BENY Apr 24 '19 at 23:00
  • @Wen-Ben Ha! For sure... – cs95 Apr 24 '19 at 23:01
  • @cs95: it seems there is a bug in version 0.21 causing `.agg(list)` errors out. However, `.agg(lambda x: list(x))` works fine. Version 0.24 works fine on both – Andy L. Apr 25 '19 at 02:46

0 Answers0