35

Here is the code that I am working with:

import pandas as pd

test3 = pd.Series([1,2,3], index = ['a','b','c'])
test3 = test3.reindex(index = ['f','g','z'])

So originally every thing is fine and test3 has an index of 'a' 'b' 'c' and values 1,2,3. But then when I got to reindex test3 I get that my values 1 2 3 are lost. Why is that? The desired output would be:

f 1
g 2
z 3
Adam Warner
  • 1,334
  • 2
  • 14
  • 30
  • 1
    The [docs](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reindex.html#pandas.Series.reindex) are clear on this behaviour :`Conform Series to new index with optional filling logic, placing NA/NaN in locations having no value in the previous index` if you just want to overwrite the index values then do `test3.index = ['f','g','z']` – EdChum Jan 30 '16 at 22:36
  • 2
    @EdChum so how would I go about filling the new index with the same values as before? – Adam Warner Jan 30 '16 at 22:37

1 Answers1

30

The docs are clear on this behaviour :

Conform Series to new index with optional filling logic, placing NA/NaN in locations having no value in the previous index

if you just want to overwrite the index values then do:

In [32]:
test3.index  = ['f','g','z']

test3
Out[32]:
f    1
g    2
z    3
dtype: int64
EdChum
  • 376,765
  • 198
  • 813
  • 562
  • I understand this. My issue is that I have a larger Dataframe called "data" and when i do ts = pd.Series(data = data['Nasdaq Composite'], index = data['Date']) I get a column of Nan where I would expect values. So i tried to create a reproducible result without putting up the dataset. – Adam Warner Jan 30 '16 at 22:43
  • 3
    Again that is the same as reindexing, if you want to create a new Series based on existing data then you need to flatten the series: `ts = pd.Series(data = data['Nasdaq Composite'].values, index = data['Date'])` will work – EdChum Jan 30 '16 at 22:47
  • thanks a lot I am very very new to python so the ".values" business did it for me. – Adam Warner Jan 30 '16 at 22:51
  • 1
    What `.values` does is return a np array, this is just an array of values, `data['Nasdaq Composite']` is a `Series` so the `Series` ctor will try to reuse the index which is why your code failed – EdChum Jan 30 '16 at 22:52