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

Split dataframe column into equal sublengths and return the new dataframe

I have a dataframe such as below and I want to split the string column into rows each with an equal string of 4 characters.

date, string
2002-06-01, 12345678
2002-06-02, 87654321

Expected Output

date, string
2002-06-01, 1234
2002-06-01, 5678
2002-06-02, 8765
2002-06-02, 4321

I have tried the example given here: Split cell into multiple rows in pandas dataframe

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

from itertools import chain

def chainer(s):
    return list(chain.from_iterable(s.str.split(df['string'], 4)))

lens = df['string'].str.split(df['string'], 4).map(len)
res = pd.DataFrame({'date': np.repeat(df['date'], lens), 'string': chainer(df['string'])})

But I get the error: TypeError: unhashable type: ‘Series’. How can I fix this issue.

>Solution :

Exlplode Chunks

df.assign(
    string=[
        [x[i:i+4] for i in range(0, len(x), 4)]
         for x in df.string]
).explode('string')

         date string
0  2002-06-01   1234
0  2002-06-01   5678
1  2002-06-02   8765
1  2002-06-02   4321
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