为了将单元格拆分为新列,我使用以下代码:
| 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;
为了取消最后一项中的分号,我该怎么办
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