2017-01-29 1 views
3

팬더 데이터 프레임이 있습니다. 열 중 하나에 중첩 목록이 있습니다. 나는 중첩 된 목록에서파이썬 중첩 목록에서 팬더에 새 열을 만듭니다.

예를 새 열을 만들 싶습니다

L = [[1,2,4], 
    [5,6,7,8], 
    [9,3,5]] 

나는 열로 중첩 된 목록의 모든 요소를 ​​원한다. 목록에 요소가 있으면 값은 1이고 그렇지 않으면 값은 0이어야합니다.

1 2 4 5 6 7 8 9 3 
1 1 1 0 0 0 0 0 0 
0 0 0 1 1 1 1 0 0 
0 0 0 1 0 0 0 1 1 

답변

2

는 다음을 시도 할 수 있습니다 : @ Psidom의 대답에

df = pd.DataFrame({"A": L}) 

df 
#   A 
#0 [1, 2, 4] 
#1 [5, 6, 7, 8] 
#2 [9, 3, 5] 

# for each cell, use `pd.Series(1, x)` to create a Series object with the elements in the 
# list as the index which will become the column headers in the result 
df.A.apply(lambda x: pd.Series(1, x)).fillna(0).astype(int) 

# 1 2 3 4 5 6 7 8 9 
#0 1 1 0 1 0 0 0 0 0 
#1 0 0 0 0 1 1 1 1 0 
#2 0 0 1 0 1 0 0 0 1 
+1

'pd.Series (1, x)'- 이것은 영리합니다! – MaxU

+0

놀라워요. 정확히 내가 원했던 것처럼! – Prasanth

+0

이 솔루션은 df의 단일 셀에서 L로 시작하지 않습니다. –

2

pandas

매우 유사한. 그러나, 나는 pd.value_counts 사용

사용 @의 Psidom의 df

df = pd.DataFrame({'A': L})  

df.A.apply(pd.value_counts).fillna(0).astype(int) 

numpy

더 복잡하지만, 빠른

lst = df.A.values.tolist() 
n = len(lst) 
lengths = [len(sub) for sub in lst] 
flat = np.concatenate(lst) 
u, inv = np.unique(flat, return_inverse=True) 
rng = np.arange(n) 
slc = np.hstack([ 
     rng.repeat(lengths)[:, None], 
     inv[:, None] 
    ]) 
data = np.zeros((n, u.shape[0]), dtype=np.uint8) 
data[slc[:, 0], slc[:, 1]] = 1 
pd.DataFrame(data, df.index, u) 

결과 반복을 처리 할

1 2 3 4 5 6 7 8 9 
0 1 1 0 1 0 0 0 0 0 
1 0 0 0 0 1 1 1 1 0 
2 0 0 1 0 1 0 0 0 1 
관련 문제