2017-02-01 3 views
1

인사말!팬더는 여러 열의 행 값을 반복적으로 추가합니다.

그룹을 기반으로 새 df에서 여러 열의 행 값을 새 열로 반복적으로 추가하려고합니다.

나의 목표는 각 고객에 대해 1 행을 가지며 고객의 ID에 대해 1 열과 각 이벤트의 날짜, 각 날짜 및 이벤트에 대한 이벤트 설명이 날짜순으로 나열된 타임 라인에 대해 1 열을 갖는 것입니다. .

나는 이것을 일련의 사전들로 해결했다. 나는 등,이 코드로 이러한 목표를 달성하기 위해 깨끗하고 우아한, 팬더 스타일의 방법을 검색하고 고객, 이벤트에 작은 변화를 자주 실행됩니다

예 :

import pandas as pd 

df_have = pd.DataFrame({'Customer_ID':['customer_1','customer_1','customer_1','customer_2','customer_2'], 
         'Event':['purchased cornflakes','purchased eggs', 'purchased waffles','sold eggs','purchased cows'], 
          'Date':['2011-06-16','2011-06-13','2011-06-09','2011-06-13','2011-06-18']}) 

df_have['Date'] = pd.to_datetime(df_have['Date']) 

df_have.sort_values(['Customer_ID','Date'], inplace =True) 
df_have 

df I currently have

df_want = pd.DataFrame({'Customer_ID':['customer_1','customer_2'], 
         'Time_Line':[['2011-06-09,purchased waffles,2011-06-13,purchased eggs,2011-06-16,purchased cornflakes'], 
            ['2011-06-13,sold eggs,2011-06-18,purchased cows']]}) 
df_want 

df I'd like to have

답변

2

단계 :

1) 작동 중에 정적으로 유지되므로 Customer_ID을 인덱스 축으로 설정하십시오. 서로 아래

2) stack가되도록 DateEvent가.

3) 인덱스 level=0groupby을 입력하고 유일한 열을 list으로 변환하십시오. 우리가이 순서대로 그들을 쌓아 왔기 때문에, 그들은 교대로 나타날 것입니다.


# set maximum width of columns to be displayed 
pd.set_option('max_colwidth', 100) 

df_have.set_index('Customer_ID').stack(
    ).groupby(level=0).apply(list).reset_index(name="Time_Line") 

enter image description here


시퀀스가 ​​list 내부에 발생 순서 변경하려면 다음 Maveli @Nickil

df_have.set_index('Customer_ID').reindex_axis(['Event', 'Date'], axis=1).stack(
    ).groupby(level=0).apply(list).reset_index(name="Time_Line") 

enter image description here

+0

덕분이 beautif이고 ul! stack()이 df_have.columns를 기반으로 주문을 선택합니까? 예를 들어 스택의 순서를 어떻게 바꿀 수 있습니까 (예 : 이벤트, 날짜, 이벤트 대신 날짜)? 열 이름의 문자열 목록을 전달하려고 시도했지만 작동하지 않습니다. –

+0

내 게시물을 업데이트했습니다. –

+1

굉장합니다. 고맙습니다. 그것은 나를 위해 직관적이지 않았습니다. –

관련 문제