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

Create multiple columns by splitting value from other column with one assignment

There is DataFrame as:

timestamp                filename
2023-12-20 10:09:52.011  2023/12/20/1703056183.log

How to create new columns "year","month","day" in one assignment by splitting of "filename" column?

Wished result is :

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

timestamp                year month day  filename
2023-12-20 10:09:52.011  2023 12    20   2023/12/20/1703056183.log

>Solution :

Use Series.str.split with n parameter for split first 3 /, for expected order add DataFrame.pop:

Notice: Filename column is changed

df[['year','month','day','filename']] = df.pop('filename').str.split('/', n=3, expand=True)
print (df)
                 timestamp  year month day        filename
0  2023-12-20 10:09:52.011  2023    12  20  1703056183.log

For your ouput with filename column in your order use:

df[['year','month','day','_']] = df['filename'].str.split('/', n=3, expand=True)

df = df[df.columns.drop(['filename','_']).union(['filename'], sort=False)]
print (df)
                 timestamp  year month day                   filename
0  2023-12-20 10:09:52.011  2023    12  20  2023/12/20/1703056183.log
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