1

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Marsh C
  • 11
  • 2

2 Answers2

0

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

  • I want to append the panda2['test'] Series multiply times to the panda1['test'] series. Therefor i use the for loop – Marsh C Jun 19 '22 at 16:24
  • @MarshC I hope now it answers your question – Ammar Sabir Cheema Jun 19 '22 at 17:21
  • Thanks for apply, but this doesnt help me in this case. In my "not-simplified" problem, the value of panda2['test'] will change every iteration of the foor lop. So it has to be the way with the for loop i described above – Marsh C Jun 19 '22 at 17:35
0

Use pd.concat

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

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

rafaelc
  • 57,686
  • 15
  • 58
  • 82
  • I do not want to concat dataframes, i want to concat Series. Because i want do it with a specific coloumn (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? – Marsh C Jun 19 '22 at 16:23