Home > database >  How to add a value and its index to a series?
How to add a value and its index to a series?

Time:11-25

I googled and most of the answers is about adding a value to a series but not update the index.

Here is my series with date string as its index like this

2022-01-01  1
2022-01-02  7
2022-01-03  3

Now I like to add new value of 10 into this series with new index of 2022-01-04 date string. so the series becomes

2022-01-01  1
2022-01-02  7
2022-01-03  3
2022-01-04  10

How to do it?

Thanks

CodePudding user response:

Just use the index value as a subscript, for example:

>>> aa = pd.Series({"foo": 1})
>>> aa
foo    1
dtype: int64
>>> aa["bar"] = 2
>>> aa
foo    1
bar    2
dtype: int64

CodePudding user response:

Is it not just something like:

new_row = pd.Series(new_value, index=[index_of_new_value])
series = pd.concat([series, new_row])

I may have misunderstood your question.

CodePudding user response:

Assuming your series is called ser, here is a proposition with pandas.DatetimeIndex and pandas.Series.reindex :

idx = pd.date_range('01-01-2022', '01-04-2022')
ser.index = pd.DatetimeIndex(ser.index)
ser = ser.reindex(idx, fill_value=10)

# Output :

print(ser)

2022-01-01     1
2022-01-02     7
2022-01-03     3
2022-01-04    10
  • Related