您可以使用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
太棒了!有用。但無論如何要做'就地'。我試圖操縱的數據框是〜20GB –
'get_dummies'是複雜的函數,所以不幸我不能幫你。 '20GB'真的很大df :( – jezrael
感謝,雖然,是的,太大了,我可能會嘗試分解它,並做它的一頓飯,或者只是更聰明地使用它的當前結構中的數據 –