简体   繁体   English

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

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

Say I have a simple data frame as below where I set the index of this dataframe to be the time column.假设我有一个简单的数据框,如下所示,我将 dataframe 的索引设置为时间列。

Eg例如

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.现在这个 dataframe 只有 1 个主列(价格),所以我想知道采用这个 dataframe 的最佳方法,只需将其类型更改为系列。

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.我觉得这可以使用 pandas squeeze()方法来完成,但是想知道是否有其他替代方法或更好的方法,如果我的方法看起来错误,也请纠正我。

Eg例如

# 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')
` ``

I think simplier is select column like:我认为更简单的是 select 列,如:

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

I think inplace is not good practice, check this and this .我认为inplace不是好习惯,请检查thisthis

df["price"] would also give you the same thing. df["price"]也会给你同样的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM