【问题标题】:How do I turn a Pandas DataFrame object with 1 main column into a Pandas Series with the index column from the original DataFrame如何将具有 1 个主列的 Pandas DataFrame 对象转换为具有原始 DataFrame 索引列的 Pandas 系列
【发布时间】:2021-02-23 11:46:13
【问题描述】:

假设我有一个简单的数据框,如下所示,我将此数据框的索引设置为时间列。

例如

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)

现在这个数据框只有 1 个主列(价格),所以我想知道获取这个数据框的最佳方法,只需将其类型更改为系列。

我觉得这可以使用 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')
` ``

【问题讨论】:

  • 我认为squeeze 没有问题。用法:df["price"].squeeze().

标签: python pandas dataframe series


【解决方案1】:

我认为更简单的是选择列,例如:

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

我认为inplace 不是好习惯,请检查thisthis

【讨论】:

  • 谢谢,但是当您选择这样的列时,它会成为一个系列吗?就像我做type(s) 一样,它会显示为一个系列而不是一个数据框吗?
  • @nishcs 当然,那么 s 就是系列。
【解决方案2】:

df["price"] 也会给你同样的东西。

【讨论】:

    猜你喜欢
    • 2021-04-29
    • 1970-01-01
    • 2019-11-28
    • 2017-09-02
    • 2016-09-24
    • 2015-08-08
    • 2017-02-18
    • 2021-11-22
    • 2020-12-31
    相关资源
    最近更新 更多