How to add unbalanced List into a dataFrame in Python?

Viewed 193

Here is My dataframe and List


X  Y  Z  X1
1  2  3  3
2  7  2  6
3 10  5  4
4  3  7  9
5  3  3  4

list1=[3,5,6]
list2=[4,3,7,4]

I want to add the lists into a data frame, I have tried some code but it gives an error and something is not working

#Expected Output

X  Y  Z  X1
1  2  3  3
2  7  2  6
3 10  5  4
4  3  7  9
5  3  3  4
3        4
5        3
6        7
         4    


#here is my code

list1 = [3,5, 6]
df_length = len(df1) 
df1.loc[df_length] = list1

Please help me to solve this problem. Thanks in advance.

2 Answers

Use series.append() to create the new series (X & X1), and create the output df using pd.concat():

s1 = df.X.append(pd.Series(list1)).reset_index(drop=True)
s2 = df.X1.append(pd.Series(list2)).reset_index(drop=True)

df = pd.concat([s1, df.Y, df.Z, s2], axis=1).rename(columns={0: 'X', 1: 'X1'})

df
    X   Y       Z   X1
0   1.0 2.0     3.0 3
1   2.0 7.0     2.0 6
2   3.0 10.0    5.0 4
3   4.0 3.0     7.0 9
4   5.0 3.0     3.0 4
5   3.0 NaN     NaN 4
6   5.0 NaN     NaN 3
7   6.0 NaN     NaN 7
8   NaN NaN     NaN 4
'''
X  Y  Z  X1
1  2  3  3
2  7  2  6
3 10  5  4
4  3  7  9
5  3  3  4
'''

list1=[3,5,6]
list2=[4,3,7,4]
ls_empty=[]

import pandas as pd
import numpy as np

df = pd.read_clipboard()


df1 = pd.DataFrame([list1, ls_empty, ls_empty, list2])
df1 = df1.T
df1.columns = df.columns

df2 = pd.concat([df, df1]).replace(np.nan, '', regex=True).reset_index(drop=True).astype({'X1': int})



print(df2)

Output:

   X   Y  Z  X1
0  1   2  3   3
1  2   7  2   6
2  3  10  5   4
3  4   3  7   9
4  5   3  3   4
5  3          4
6  5          3
7  6          7
8             4
Related