Home > Mobile >  How to add lists of varying lengths as rows to a DataFrame
How to add lists of varying lengths as rows to a DataFrame

Time:11-26

I have lots of lists that I need to combine into a DataFrame, each as a row. The lists are of 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)

CodePudding user response:

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
  • Related