Warm tip: This article is reproduced from serverfault.com, please click

Pandas Series object does not update values

发布于 2020-12-14 13:00:08

I got a Pandas Series object looks like following:

(Pdb) data1
date_time
2019-12-31 01:00:00+00:00    1.0
2019-12-31 02:00:00+00:00    1.0
2019-12-31 03:00:00+00:00    1.0
2019-12-31 04:00:00+00:00    1.0
2019-12-31 05:00:00+00:00    1.0
                              ...
2020-11-30 20:00:00+00:00    5.0
2020-11-30 21:00:00+00:00    20.0
2020-11-30 22:00:00+00:00    20.0
2020-11-30 23:00:00+00:00    20.0
2020-12-01 00:00:00+00:00    20.0
Name: ASD, Length: 8064, dtype: float64

values of the object:

(Pdb) data1.values
array([1., 1., 1., ..., 20., 20., 20.])

if I run a function on data1.values called shift()

(Pdb) shift(data1.values, -1)
array([1., 1., 1., ..., 20., 20., 0.])

The function basically shifts the array its given as input. My question is why pandas Series update() function does not work as intended?

(Pdb) data1.update(shift(data1.values, -1))
(Pdb) data1
date_time
2019-12-31 01:00:00+00:00    1.0
2019-12-31 02:00:00+00:00    1.0
2019-12-31 03:00:00+00:00    1.0
2019-12-31 04:00:00+00:00    1.0
2019-12-31 05:00:00+00:00    1.0
                              ...
2020-11-30 20:00:00+00:00    20.0
2020-11-30 21:00:00+00:00    20.0
2020-11-30 22:00:00+00:00    20.0
2020-11-30 23:00:00+00:00    20.0
2020-12-01 00:00:00+00:00    20.0
Name: DEtoDK, Length: 8064, dtype: float64

It should actually add a 0 in the end and shift the series values. Why I cant do that?

Questioner
oakca
Viewed
0
coco18 2020-12-14 21:47:59

Normaly there is a build up function shift() in pandas DataFrame:

you can try the following code:

data1 = data1.shift(-1)

This code shift all columns by 1

If you like to shift only one column, you should name the column with the values and call the following code

data1[columns_name] = data1[columns_name].shift(-1)