我有以下内容df:
df = pd.DataFrame({'Category': ['root:catA', 'root:catA:catB'], 'Age':[32, 34]})
Run Code Online (Sandbox Code Playgroud)
现在我要进行拆分的列Category由:进,共4个,列。由于row0将导致4个填充列,而row1在5个填充列中,因此列数将减少,因此其余列应使用填充NaN。
预期产量:
df = pd.DataFrame({'Category': ['root:catA', 'root:catA:catB'], 'Age':[32, 34], 'Cat1':['root', 'root'], 'Cat2':['catA', 'catA'], 'Cat3':['NaN', 'CatB'], 'Cat4':['NaN', 'NaN']})
Run Code Online (Sandbox Code Playgroud)
我尝试了以下方法:
df[['cat1','cat2', "cat3", "cat4"]] = df.Category.str.split(":",expand=True)
Run Code Online (Sandbox Code Playgroud)
但是我得到了
ValueError: Columns must be same length as key