0

I have a dataframe with multiple transactions of each customer

ID   Date of visit
123 08/09/2013
123 01/02/2014
123 08/08/2014
123 12/03/2017
abd 01/09/2016

I want to aggregate the record in such a way that my dataframe looks like

ID   First visit   Second visit   Third visit
123 08/09/2013     01/02/2014    08/08/2014

Is it possible do like this? I have one million records wit 30,000 customer. How do I approach the problem

asspsss
  • 103
  • 1
  • 1
  • 8
  • See Q10 in [this question](https://stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe), exchange `index` and `columns` – Quang Hoang Oct 08 '19 at 20:40

2 Answers2

1

Use:

new_df=df.groupby('ID').apply(lambda x: x['Date_of_visit'].reset_index(drop=True)).unstack()
new_df.columns=  ['Visit_'+str(key+1) for key in new_df.columns]
print(new_df)

        Visit_1     Visit_2     Visit_3     Visit_4
ID                                                 
123  08/09/2013  01/02/2014  08/08/2014  12/03/2017
abd  01/09/2016         NaN         NaN         NaN
ansev
  • 30,322
  • 5
  • 17
  • 31
0

One way to do it is to concat nth(i)

enter image description here