2 回答

TA貢獻1785條經(jīng)驗 獲得超8個贊
想法是添加元組 if 標量然后創(chuàng)建新列:
def f(col):
return pd.DataFrame([x if isinstance(x, tuple) else (x, )
for x in col]).fillna(0).astype(int)
df[['w', 'x']]=df.pop('a').pipe(f)
df[['y', 'z']]=df.pop('b').pipe(f)
print (df)
w x y z
0 0 1 1 0
1 1 0 1 2
2 2 0 3 0
更通用的解決方案concat:
dfs= [pd.DataFrame([x if isinstance(x, tuple) else (x, ) for x in df.pop(c)],
index=df.index) for c in df.columns]
df = pd.concat(dfs, axis=1, ignore_index=True).fillna(0).astype(int)
print (df)
0 1 2 3
0 0 1 1 0
1 1 0 1 2
2 2 0 3 0

TA貢獻1817條經(jīng)驗 獲得超14個贊
您可以轉(zhuǎn)換為,然后str轉(zhuǎn)換strip為()split,
>>> df[['w', 'x']] = pd.DataFrame(df.pop('a')
.astype(str)
.str.strip('(/)')
.str.split(',')
.tolist()).fillna(0).astype(int)
>>> df[['y', 'z']] = pd.DataFrame(df.pop('b')
.astype(str)
.str.strip('(/)')
.str.split(',')
.tolist()).fillna(0).astype(int)
>>> df
w x y z
0 0 1 1 0
1 1 0 1 2
2 2 0 3 0
添加回答
舉報