Let’s say my dataframe is like this:
Used the following code to split data inside each column:
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:
But now after adding list comprehension it looks like:
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(*(........))


