2017-04-21 66 views
1

我確信無需使用嵌套循環就可以做到這一點。將Dataframe列的內容「擴展」到新列中

我有一個DF(注意,對字符串列表的列)

df = DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3,5], 'C' : [['a','b'],['b','c'] ,['g','h'],['x','y']]}) 

最終我想「擴大」出來在列列表中的值,以便有針對每一個山坳可能的列表項目,並且對於每一行,如果該值出現,則在正確列中有1。例如

df = 

A B  C  a b c g h x y 
5 1 ['a','b'] 1 1 
6 2 ['b','c']  1 1 
3 3 ['g','h']   1 1 
4 5 ['x','y']     1 1 

回答

1

您可以使用pandas.get_dummies,但隨後被columns和彙總max需要groupby

df1 = pd.get_dummies(pd.DataFrame(df.C.values.tolist()), prefix='', prefix_sep='') 
     .groupby(axis=1, level=0).max() 

df1 = pd.concat([df, df1], axis=1) 
print (df1) 

    A B  C a b c g h x y 
0 5 1 [a, b] 1 1 0 0 0 0 0 
1 6 2 [b, c] 0 1 1 0 0 0 0 
2 3 3 [g, h] 0 0 0 1 1 0 0 
3 4 5 [x, y] 0 0 0 0 0 1 1 

replace + str.get_dummies另一種解決方案:

df1 = df.C.astype(str).replace(['\[','\]', "'", "\s+"], '', regex=True).str.get_dummies(',') 
df1 = pd.concat([df, df1], axis=1) 
print (df1) 

    A B  C a b c g h x y 
0 5 1 [a, b] 1 1 0 0 0 0 0 
1 6 2 [b, c] 0 1 1 0 0 0 0 
2 3 3 [g, h] 0 0 0 1 1 0 0 
3 4 5 [x, y] 0 0 0 0 0 1 1 

也可以去除0,但用數字和一些熊貓函數獲取字符串值c被打破:

df1 = df.C.astype(str).replace(['\[','\]', "'", "\s+"], '', regex=True).str.get_dummies(',') 
df1 = df1.replace(0,'') 
df1 = pd.concat([df, df1], axis=1) 
print (df1) 
    A B  C a b c g h x y 
0 5 1 [a, b] 1 1    
1 6 2 [b, c]  1 1    
2 3 3 [g, h]   1 1  
3 4 5 [x, y]     1 1 
+0

太棒了!有用。但無論如何要做'就地'。我試圖操縱的數據框是〜20GB –

+0

'get_dummies'是複雜的函數,所以不幸我不能幫你。 '20GB'真的很大df :( – jezrael

+0

感謝,雖然,是的,太大了,我可能會嘗試分解它,並做它的一頓飯,或者只是更聰明地使用它的當前結構中的數據 –