roudan
roudan

Reputation: 4208

How to add a value and its index to a series?

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

Upvotes: 1

Views: 116

Answers (3)

Timeless
Timeless

Reputation: 37787

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

Upvotes: 0

msailor
msailor

Reputation: 340

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

Upvotes: 2

butterflyknife
butterflyknife

Reputation: 1574

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.

Upvotes: 1

Related Questions