suziex
suziex

Reputation: 72

How to add new data to existing dataframe

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?

Upvotes: 0

Views: 76

Answers (1)

jezrael
jezrael

Reputation: 863501

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)

Upvotes: 1

Related Questions