How Can I Split A Column Into 2 In The Correct Way In Python?
I am web-scraping tables from a website, and I am putting it to the Excel file. My goal is to split a columns into 2 columns in the correct way. The columns what i want to split: '
Solution 1:
You can use str.split
- n=1
for split by first whitespace and expand=True
for return DataFrame
, which can be assign to new columns:
df2[['c','d']] = df2['STATUS'].str.split(n=1, expand=True)
Sample:
df2 = pd.DataFrame({'STATUS':['Estimated 3:17 PM','Delayed 3:00 PM']})
df2[['c','d']] = df2['STATUS'].str.split(n=1, expand=True)
print (df2)
STATUS c d
0 Estimated 3:17 PM Estimated 3:17 PM
1 Delayed 3:00 PM Delayed 3:00 PM
If no whitespace in input get None
in output:
df2 = pd.DataFrame({'STATUS':['Estimated 3:17 PM','Delayed 3:00 PM', 'Canceled']})
df2[['c','d']] = df2['STATUS'].str.split(n=1, expand=True)
print (df2)
STATUS c d
0 Estimated 3:17 PM Estimated 3:17 PM
1 Delayed 3:00 PM Delayed 3:00 PM
2 Canceled Canceled None
and if need replace None
to empty string use fillna
:
df2[['c','d']] = df2['STATUS'].str.split(n=1, expand=True)
df2['d'] = df2['d'].fillna('')
print (df2)
STATUS c d
0 Estimated 3:17 PM Estimated 3:17 PM
1 Delayed 3:00 PM Delayed 3:00 PM
2 Canceled Canceled
Post a Comment for "How Can I Split A Column Into 2 In The Correct Way In Python?"