如何用python拆分excel表格中的句子?

2024-04-19 13:55:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张excel表格:

enter image description here

从第一张excel表格开始,我想再制作一张这样的excel表格:

enter image description here

下面是python代码来拆分一个句子,但是我不能用excel表来拆分。在

    import xlrd
    import pandas as pd
    b=xlrd.open_workbook("sample_docu5.xlsx")
    p=b.sheet_by_index(0)
    #open("sample_docu5.xlsx") as f:
    s=  "Dead poet society, Julia Roberts, London"
    line=s.split(',')
    print (line)

输出:

^{pr2}$

Tags: sample代码imageimporthereaslinedescription
1条回答
网友
1楼 · 发布于 2024-04-19 13:55:38

使用Pandas,您可以在excel文件中读取数据,拆分列,将它们存储在Pandas数据框中,然后将该数据框写入新的excel文件。在

import pandas as pd
#Read in your dataset with the 2 headers
df = pd.read_excel(r'sample_docu5.xlsx')

#Split out the first column into 3 different columns
df['Title'], df['Actor'],df['Place'] = df['All'].str.split(',', 2).str

#Delete the 'All' column as we have created 3 new columns
del df['All']

#Reorder the columns
df = df[['Title','Actor','Place','Document_Source']]
df.to_excel('output.xlsx')
df.head()

相关问题 更多 >