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

How to multipy values splited from str in DataFrame, Python?

For example DataFrame:

import pandas as pd

df = pd.DataFrame.from_dict({
    'art1':['n1','n2'],
    'sizes':['35 36 37', '36 38']
    })

print (df)

# need that

df_result = pd.DataFrame.from_dict({
    'art1':['n1','n1','n1','n2','n2'],
    'sizes':[35,36,37,36,38]
})
        
print (df_result)

BELOW IS CORRECT BUT NOT EFFICIENT DECISION !!!

lst_art = []
lst_sizes = [x.split() for x in df['sizes']]
for i in range(len(lst_sizes)):
    for j in range(len(lst_sizes[i])):
        lst_art.append(df['art1'][i])

lst_sizes = sum(lst_sizes, [])
df = pd.DataFrame({'art1':lst_art, 'sizes':lst_sizes})

print (df)

any pandas efficient way to get df_result from df?

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

>Solution :

You can first split the string column into a list and then you can explode each item in the list into a new row

df = pd.DataFrame.from_dict({
    'art1':['n1','n2'],
    'sizes':['35 36 37', '36 38']
    })

# convert str to list
df['sizes'] = df['sizes'].str.split()

# create one new row per item in list of `sizes`
df_result = df.explode('sizes')

or you can do an overly powerful one liner

df.assign(sizes=df['sizes'].str.split()).explode('sizes')
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