2016-12-02 5 views
1

팬더 데이터 프레임이 있고 사용하려는 열의 값이 목록입니다. 두 목록을 하나씩 결합하여 다른 DataFrame으로 출력하고 싶습니다.
예를 들어 col_acol_b을 포함하는 데이터 프레임 df이 있습니다. col_b의 값은 목록입니다. df.col_b의 값을 루프하고 쌍을 이루는 목록을 출력하고 싶습니다.팬더 루프 열의 값

import pandas as pd 

df=pd.DataFrame({'col_a':['ast1','ast2','ast3'],'col_b':[['text1','text2','text3'],['mext1','mext2','mext3'],['cext1','cext2']]}) 
df 

    col_a col_b 
0 ast1 [text1, text2, text3] 
1 ast2 [mext1, mext2, mext3] 
2 ast3 [cext1, cext2] 

나는이 원하는 :

col_a col_b_1 
0 ast1 [text1, text2] 
1 ast1 [text1, text3] 
2 ast1 [text2, text3] 
3 ast2 [mext1, mext2] 
4 ast2 [mext1, mext3] 
5 ast2 [mext2, mext3] 
6 ast3 [cext1, cext2] 

답변

1

가정하여 col_a가 행마다 고유 한 값, 목록 요소의 모든 두 개의 조합을 생성하는 itertools에서 combinations를 사용할 수 있습니다

from itertools import combinations 
(df.groupby('col_a')['col_b'] 
    .apply(lambda x: pd.Series(list(combinations(x.iloc[0], 2)))) 
    .reset_index(level = 0)) 

# col_a   col_b 
#0 ast1 (text1, text2) 
#1 ast1 (text1, text3) 
#2 ast1 (text2, text3) 
#0 ast2 (mext1, mext2) 
#1 ast2 (mext1, mext3) 
#2 ast2 (mext2, mext3) 
#0 ast3 (cext1, cext2) 
1

itertools을 사용하여 목록을 병합 할 수 있습니다.

import itertools 
series = df["col_b"].apply(lambda x: \ 
    pd.Series(list(itertools.combinations(x,2)))).stack() 

시리즈는 "어머니"dataframe와 병합 가능으로 이름이 있어야합니다 : 두 데이터 객체의 병합, 지금

series.name = "col_b_1" 

하고 원하는 열을 선택 :

result = df.merge(pd.DataFrame(series).reset_index(), 
    left_index=True, 
    right_on="level_0")[["col_a","col_b_1"]] 

결과는 튜플 열입니다. 이게 좋지 않으면 .apply() 기능이 list()입니다.

# col_a   col_b_1 
# 0 ast1 (text1, text2) 
# 1 ast1 (text1, text3) 
# 2 ast1 (text2, text3) 
# 3 ast2 (mext1, mext2) 
# 4 ast2 (mext1, mext3) 
# 5 ast2 (mext2, mext3) 
# 6 ast3 (cext1, cext2) 
관련 문제