Home > other >  Append a list to a existing dataframe
Append a list to a existing dataframe

Time:04-08

I have a dataframe as shown below:

df = 

                             A     B     
timestamp               
2022-04-08 10:07:00 29.504  50  0.85
2022-04-08 10:07:01 29.731  52  0.83
2022-04-08 10:07:02 29.393  53  0.84

I have a list as shown:

B = 
[[0, 5],
 [10, 1],
 [1,40]]

I want to append the list to the dataframe like this

df = 

                             A     B    0    1
timestamp               
2022-04-08 10:07:00 29.504  50  0.85    0    5
2022-04-08 10:07:01 29.731  52  0.83    10   1
2022-04-08 10:07:02 29.393  53  0.84    1    40

I order to do this, I converted the list to a dataframe

C = pd.DataFrame(B)
C =
    0   1
0   0   5
1   10  1
2   1   40

In order to obtain the desired result, I tried pd.concat and pd.append. Both of the techniques did not work. The dataframe df has a timestamp as index and the dataframe C does not have timestamp index. Therefore I am finding it difficult to concatenate or append these two dataframe. Can somebody help me with a solution?

CodePudding user response:

You could assign B to two columns:

df[[0,1]] = B

Output:

                             A     B   0   1
timestamp                                   
2022-04-08 10:07:00 29.504  50  0.85   0   5
2022-04-08 10:07:01 29.731  52  0.83  10   1
2022-04-08 10:07:02 29.393  53  0.84   1  40

CodePudding user response:

You can reset_index the first df and then do pd.concat like this,

pd.concat([df.reset_index(), pd.DataFrame(B)], axis=1).set_index("timestamp")

You can later set the index for the resulting dataframe as timestamp

CodePudding user response:

Use:

pd.concat([df, pd.DataFrame(B)], axis = 1)

Demonstration:

cols = ['A', 'B', 'timestamp']              
data = """2022-04-08 10:07:00 29.504  50  0.85
2022-04-08 10:07:01 29.731  52  0.83
2022-04-08 10:07:02 29.393  53  0.84"""
data = [x.split('  ') for x in data.split('\n')]
df = pd.DataFrame(data, columns = cols)
B = [[0, 5],
 [10, 1],
 [1,40]]
pd.concat([df, pd.DataFrame(B)], axis = 1)

Output:

enter image description here

CodePudding user response:

I believe what you need is this:

df_add = pd.concat(frames, axis=1)

where frames=[df, B]

this example should help you to do what you need:

import pandas as pd

df1 = pd.DataFrame([(1,2),(3,4),(5,6)], columns=['a','b'])

df2 = pd.DataFrame([(100,200),(300,400),(500,600)], columns=['a','b'])

frames = [df1, df2]
df_add = pd.concat(frames, axis=1)

print(df_add)
  • Related