Home > OS >  Appending Pandas Series to a Serie in a for loop
Appending Pandas Series to a Serie in a for loop

Time:06-20

I want to grow a serie in a for loop like that:

panda1 = pd.DataFrame([1, 2 ,3], columns=['test']) 
panda2 = pd.DataFrame(['a', 'b', 'c'], columns=['test'])

for i in range(1,3):
    panda1['test'] = panda1['test'].append(panda2['test'], ignore_index=True)

I want that panda1['test'] contains [1, 2, 3, a, b, c, a, b, c]. But it only contains [1, 2, 3]

What am I doing wrong here?

Edit: I do not want to concat dataframes, I want to concat series. Because I want do it with a specific column (in the example it is ['test']). I know that concat can handle series, too. But when i do it with the ['test'] series, the same happens what i described above. When i do the concat with the whole dataframe panda1 and panda2 without the '['test']', it works properly. Why does it not work with Series?

CodePudding user response:

Use pd.concat

pd.concat([panda1, panda2], axis=0)

You can also set axis=1 for row-wise concatenation.

CodePudding user response:

You don't need to loop to add the second dataframe, you can append the second dataframe as given below,

>>> panda1 = pd.DataFrame([1, 2 ,3], columns= 
['test']) 
>>> panda1
    test
0     1
1     2
2     3
>>> panda2 = pd.DataFrame(['a', 'b', 'c'], 
columns=['test'])
>>> panda2
   test
0    a
1    b
2    c

>>> n=2 # number of times you want to append the panda2 dataframe 
>>> panda1.append([panda2]*n, ignore_index=True)
   test
0    1
1    2
2    3
3    a
4    b
5    c
6    a
7    b
8    c

As given from here and here

  • Related