簡體   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

假設我有一個簡單的數據框,如下所示,我將 dataframe 的索引設置為時間列。

例如

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)

現在這個 dataframe 只有 1 個主列(價格),所以我想知道采用這個 dataframe 的最佳方法,只需將其類型更改為系列。

我覺得這可以使用 pandas squeeze()方法來完成,但是想知道是否有其他替代方法或更好的方法,如果我的方法看起來錯誤,也請糾正我。

例如

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

我認為更簡單的是 select 列,如:

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

我認為inplace不是好習慣,請檢查thisthis

df["price"]也會給你同樣的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM