Add a new value at the beginning of a pandas series

Asked

Viewed 1,095 times

2

How do I add a new value to a pandas series?

I made the copy of the dataframe series and now I need to add a new value to the series swap_hoje, but instead of being at the end of the series, I need it to be at the beginning, in the index 0.

swap_hoje = swap_dataframe['Valor'].reset_index(drop=True)

I also need to add a value to the series swap_ontem:

swap_ontem = swap_dataframe['Valor'].reset_index(drop=True)

However, the latter will have to be at the end of the series.

2 answers

1


Edited (Insertion in the middle of the series):
I did an analysis in the middle of the series, see in the code.

Try the code below, see it running here.

import pandas as pd
serie = pd.Series()

for n in range(5):
    serie = serie.set_value(n, n*n)

# Antes da inserção
print (serie)

Output:

0     0
1     1
2     4
3     9
4    16
dtype: int64

Insertion and append:

# Convert a serie em uma lista
lst = serie.tolist()

# faz a inserção na lista
lst.insert(0,999)

# Inserindo na posição 3
lst.insert(3,'Inserção na posição 3')

# Faz append na lista
lst.append(1000)

# Converte a lista para serie
serie = pd.Series(lst)

# Pos inserção/append
print(serie)

Output:

0                      999
1                        0
2                        1
3    Inserção na posição 3
4                        4
5                        9
6                       16
7                     1000
dtype: object

DEMO

  • In fact, what your code does is replace the value of position 0, right? I believe I didn’t express myself clearly! I need a new value to be inserted in heading 0, and the old value of heading 0 to heading 1 and so on.

  • It’s like if you gave an append, only instead of the new value entering at the end of the series, it enters at the beginning!

  • I got it, actually I just didn’t pay enough attention, so... there goes a new version.

  • See if the new version meets.

1

Using the created series in this answer:

import pandas as pd
serie = pd.Series()
for n in range(5):
    serie = serie.set_value(n, n*n)

serie
0     0
1     1
2     4
3     9
4    16
dtype: int64

serie2 = pd.Series(100)
serie2
0    100
dtype: int64

serie.append(serie2, ignore_index=True)
0      0
1      1
2      4
3      9
4     16
5    100
dtype: int64

serie2.append(serie, ignore_index=True)
0    100
1      0
2      1
3      4
4      9
5     16
dtype: int64

Browser other questions tagged

You are not signed in. Login or sign up in order to post.