How do I turn a Pandas DataFrame object with 1 main column into a Pandas Series with the index column from the original DataFrame

Viewed 81

Say I have a simple data frame as below where I set the index of this dataframe to be the time column.

E.g

import pandas as pd

df = pd.DataFrame({'time':['2021-02-20','2021-02-21','2021-02-22','2021-02-23'], 'price':[1,2,3,4]})
df.set_index('time', inplace=True)

Now this dataframe as only 1 main column (price) so I want to know the best way to take this dataframe and simply change its type to a series.

I feel like this can be done using the pandas squeeze() method however want to know if there are any other alternatives or better ways, also correct me if my method seems wrong.

E.g

# Setting the original DataFrame to a Series, since only 1 main column can use the 'column' argument
# in the squeeze method 

df = df.squeeze('columns')
` ``

2 Answers

I think simplier is select column like:

s = df.set_index('time')['price']

I think inplace is not good practice, check this and this.

df["price"] would also give you the same thing.

Related