Shamoon
Shamoon

Reputation: 43501

How can I convert a Pandas Series to a Numpy Array and maintain order?

I have a pandas series that looks like:

cash          50121.599128
num_shares      436.000000
cost_basis      114.400002
open_price      113.650002
close_10        114.360001
close_9         115.769997
close_8         114.800003
close_7         114.040001
close_6         115.680000
close_5         115.930000
close_4         115.430000
close_3         113.339996
close_2         114.870003
close_1         114.050003
dtype: float64

I want to convert it to a numpy array, so I'm doing:

next_state_val = np.array([next_state.values])

However, there's no guarantee that my series will always have the same order. How can I maintain the same order across many series?

Upvotes: 0

Views: 871

Answers (2)

Itamar Mushkin
Itamar Mushkin

Reputation: 2905

If I understand the docs correctly, the .values method returns an array and preserves order.

Upvotes: 2

Christoph Burschka
Christoph Burschka

Reputation: 4689

Assuming the indices are always the same (but not necessarily occurring in the same order), you can use .sort_index() on the series. This will ensure the series is consistently ordered by its index each time.

https://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.Series.sort_index.html

Upvotes: 4

Related Questions