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

List comprehension not working as intended

Let’s say my dataframe is like this:

enter image description here

Used the following code to split data inside each column:

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

    col_names = ['col1','col2','col3']
    for i in range(len(df)):
        s = tuple(zip(df[col_names[0]].str.split(",")[i],df[col_names[1]].str.split(",")[i],df[col_names[2]].str.split(",")[i])

I changed this code so that it works dynamically to work for a variable number of columns in col_names using list comprehension as seen below:

for i in range (len(df)):
    s = tuple(zip(df[col].str.split(",")[i] for col in col_names)

Initial code used to give output as:

enter image description here

But now after adding list comprehension it looks like:

enter image description here

what is wrong in this code?

>Solution :

#1) Your code is extremely inefficient since its calling df[col].str.split(",") over and over again for every i.

#2) Your immediate bug is the zip. You are passing it a single iterator as an argument. You need to pass it multiple arguments. The correct way to convert is zip(*(........))

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