Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Pandas – Splitting a column

I am trying to split a column from a CSV file. The first column contains a date (YYmmdd) and then time (HHmmss) so the string looks like 20221001131245. I want to split this so it reads 2022 10 01 in one column and then 13:12:45 in another.

I have tried the str.split but I recognise my data isn’t in a string so this isn’t working.

Here is my code so far:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import pandas as pd
 
CSVPath = "/Desktop/Test Data.csv"
data = pd.read_csv(CSVPath)
 
print(data)

>Solution :

Use to_datetime combined with strftime:

# convert to datetime
s = pd.to_datetime(df['col'], format='%Y%m%d%H%M%S')
# or if integer as input
# s = pd.to_datetime(df['col'].astype(str), format='%Y%m%d%H%M%S')

# format strings
df['date'] = s.dt.strftime('%Y %m %d')
df['time'] = s.dt.strftime('%H:%M:%S')

Output:

              col        date      time
0  20221001131245  2022 10 01  13:12:45

alternative

using string slicing and concatenation

s = df['col'].str
df['date'] = s[:4]+' '+s[4:6]+' '+s[6:8]
df['time'] = s[8:10]+':'+s[10:12]+':'+s[12:]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading