text to columns with comma delimiter using python

2019-09-17 01:47发布

问题:

how to divide a column in to two columns in an excel using a delimiter ', 'and name the header's using python

here is my code

import openpyxl


w=openpyxl.load_workbook('DDdata.xlsx')
active=w.active


a=active.columns[1]
for cellobj in a:
    s=cellobj.value
    fila=s.split(',')

    print(fila)

Input file link

outputfile

回答1:

This looks to be a duplicate of this post, but here's a solution for you to consider:

import pandas as pd

df = pd.read_excel('input.xlsx')

df['First Name'], df['Last Name'] = df['Applicant Name'].str.split(',', 1).str
del df['Applicant Name']

df.to_excel('output.xlsx')

Output (in python):

First Name  Last Name
0   -   Mohammed Abdul Naser Aziz
1   -   Gottipati Harshavardhan
2   -   Sandeep Kaur
3   .   Rounak
4   abbas   Syed
5   Abbas   Mohd Manzar
6   Abbasi  Fatema
7   Abdelkader  BEKHTIE
8   abdollahzadehkan    mina