小编Sar*_*aha的帖子

熊猫:将细胞分裂成多个列,写为NaN

我有以下内容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

python dataframe pandas

4
推荐指数
1
解决办法
40
查看次数

标签 统计

dataframe ×1

pandas ×1

python ×1