Home > OS >  How to add new data to existing dataframe
How to add new data to existing dataframe

Time:11-28

I've created empty dataframe that I have to fill.

d = {'A': [], 'B': [], 'C': []}
dataframe = pd.DataFrame(data=d)

Then I am assigning data like this:

dataframe['A'] = some_list_1a
dataframe['B'] = some_list_1b
dataframe['C'] = some_list_1c

So my dataframe is filled like this:

 A      B     C
----------------
val1  val1  val1
val1  val1  val1
val1  val1  val1

Then I have to add new values from list but the previous way is not working: dataframe['A'] = some_list_2a etc.

That's what I want:

 A      B     C
----------------
val1  val1  val1
val1  val1  val1
val1  val1  val1
val2  val2  val2
val2  val1  val2
val2  val2  val2

(val1 - values from first lists, val2 - values from second lists)

I know I can make second dataframe and use concat method, but is there another way of doing it?

CodePudding user response:

Create dictionary with all joined lists first and then call DataFrame is fastest and recommended way, check this:

d = {'A': some_list_1a   some_list_2a, 
     'B': some_list_1b   some_list_2b,
     'C': some_list_1c   some_list_2c}
dataframe = pd.DataFrame(data=d)

If need append dict of list in loop:

from collections import defaultdict

d = defaultdict(list)

#some loop
for x in iter:
    d[col_name].append(sublist)
    
dataframe = pd.DataFrame(data=d)

CodePudding user response:

append() function is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object. Columns not in the original dataframes are added as new columns and the new cells are populated with NONE value.

  • Related