【问题标题】:pct_change() not working on dataframe. str & str errorpct_change() 不适用于数据框。 str 和 str 错误
【发布时间】:2018-02-05 03:23:41
【问题描述】:

我正在计算 PG & BEI.DE 的股票价格回报

returns = frame.pct_change() 不支持的操作数类型 /: 'str' 和 'str' 错误。我的工作是制作字典,然后传递字典中的每一列并应用 pct_change、mean 或 media 或 cov 等函数。

在示例中,我跟随讲师将函数直接应用于数据框。为什么我的数据单元格被视为字符串而不是数字? 我有一个解决方法,但我对它不满意?

【问题讨论】:

  • 这可能是因为你有字符串而不是数字。试试 frame.astype(float).pct_change()。如果这不起作用尝试 frame.apply(pd.to_numeric, errors='coerce')
  • 我有一列日期,建议的解决方案都不起作用:( ValueError: could not convert string to float: '2018-02-02'
  • 如何截断日期列?

标签: python pandas


【解决方案1】:

假设您正在使用 pandas DataFrame,那么我首先在​​ DataFrame 上调用 info

In [1]: type(frame)
Out[1]: pandas.core.frame.DataFrame

In [2]: frame.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 2 columns):
Close    5 non-null object
Date     5 non-null object
dtypes: object(2)
memory usage: 160.0+ bytes

这里有一个 DataFrame,但收盘价不是数值。因此,我们可以通过将“关闭”列强制为浮点数,将 pct_change 直接计算到 DataFrame 的新列中,如下所示:

In [3]: frame['% change'] = frame['Close'].astype(float).pct_change()

In [4]: frame
Out[4]: 
    Close        Date  % change
0  167.96  2018-01-29       NaN
1  166.97  2018-01-30 -0.005894
2  167.43  2018-01-31  0.002755
3  167.78  2018-02-01  0.002090
4  160.37  2018-02-02 -0.044165

但您可能希望将您的 DataFrame 转换为正确的类型,开始时...所以您可以执行以下操作:

In [5]: frame['Close'] = frame['Close'].astype(float)
In [6]: frame['Date'] = pd.to_datetime(frame['Date'])
In [7]: frame.set_index('Date', inplace=True)
In [8]: frame.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 5 entries, 2018-01-29 to 2018-02-02
Data columns (total 2 columns):
Close       5 non-null float64
% change    4 non-null float64
dtypes: float64(2)
memory usage: 120.0 bytes

【讨论】:

    猜你喜欢
    • 2019-01-03
    • 1970-01-01
    • 2021-06-18
    • 2017-05-27
    • 2022-12-04
    • 2018-08-22
    • 2018-11-19
    • 2011-09-05
    • 1970-01-01
    相关资源
    最近更新 更多