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 add lists of varying lengths as rows to a DataFrame

I have oodles of lists that I need to combine into a DataFrame, each as a row. The lists are varying lengths. The column names will just be index numbers but I don’t know how to dynamically generate them as needed.

l1 = [1,2,3]
l2 = [10,22,13,4]
l3 = [2]
df = pd.DataFrame()
df.loc[len(df)] = pd.DataFrame(l1, columns=list(range(len(l1))))

I get this error: ValueError: Shape of passed values is (3, 1), indices imply (3, 3)

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 :

Just pass the lists directly to the DataFrame constructor:

l1 = [1,2,3]
l2 = [10,22,13,4]
l3 = [2]
df = pd.DataFrame([l1, l2, l3])

Output:

>>> df
    0     1     2    3
0   1   2.0   3.0  NaN
1  10  22.0  13.0  4.0
2   2   NaN   NaN  NaN

If you need to append the rows one-by-one, you can you DataFrame.append:

df = pd.DataFrame()
for lst in [l1, l2, l3]:
    df = df.append([lst], ignore_index=True)

Output:

>>> df
    0     1     2    3
0   1   2.0   3.0  NaN
1  10  22.0  13.0  4.0
2   2   NaN   NaN  NaN
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