分成新列

问题描述 投票:1回答:1

为了将单元格拆分为新列,我使用以下代码:

   | Column1       | Column2
   | a;b;c;d;e;f   | 1;2;3;4

df = pd.read_excel('FileName.xlsx')
new = df["Column1"].str.split(";", n=5, expand=True).
df['1st'] = new[0]
df['2nd'] = new[1]
df['3rd'] = new[2]
df['4th'] = new[3]
df['5th'] = new[4]
df['6th'] = new[5]
df.drop(columns=["Column1"], inplace=True)

输出将变为

 Column:   1st 2nd 3rd 4th 5th 6th 
             a   b   c   d   e   f;

为了取消最后一项中的分号,我该怎么办

python pandas split multiple-columns
1个回答
0
投票
您很可能在提问中打错了字。我敢打赌,当您读入数据时,

f后面会有一个分号,并且它看起来像这样:

Column1 Column2 0 a;b;c;d;e;f; 1;2;3;4

not此:

Column1 Column2 0 a;b;c;d;e;f 1;2;3;4
因此,如果将n=6设置为n=5,则应删除最后的分号。复制我包含在上面答案中的第一个数据帧,并使用下面的df = pd.read_clipboard('\s+\s+')运行下面的代码:

import pandas as pd df = pd.read_clipboard('\s+\s+') new = df["Column1"].str.split(";", n=6, expand=True) df['1st'] = new[0] df['2nd'] = new[1] df['3rd'] = new[2] df['4th'] = new[3] df['5th'] = new[4] df['6th'] = new[5] df.drop(columns=["Column1", "Column2"], inplace=True) df

© www.soinside.com 2019 - 2024. All rights reserved.