【问题标题】:Adding a column for percent change to csv file using existing columns使用现有列将百分比更改列添加到 csv 文件
【发布时间】:2021-02-27 03:22:44
【问题描述】:

我有一个包含 2 列(日期和股票价格)的 csv 文件,我想计算百分之一的变化并添加一个新列。我想这样做是因为在此之后我想将数据分组为正百分比变化和百分比变化。

datafile = "file.csv"
import pandas as pd
df = pd.read_csv('file.csv',na_values='null')

到目前为止,我尝试了这些,但都失败了

1.

x = df.pct_change()
df["1 day percent change"] = x

TypeError: /: 'str' 和 'str' 的操作数类型不受支持

2.

df["1 day percent change"] = ((np.diff(df))/(df[:,1:]))

TypeError: 不支持的操作数类型 -: 'float' 和 'str'

3.

new_column = ((np.diff(df))/(df[:,1:]))
df = df.merge(new_column, left_index=True, right_index=True)

TypeError: 不支持的操作数类型 -: 'float' 和 'str'

你能帮我找出问题吗?谢谢!

原来的df是这样的

【问题讨论】:

  • 请提供您的 df 的打印文本样本
  • 另外,请提供失败的上下文。结果不是预期的?错误?
  • 尝试指定目标列:df["1 day percent change"] = df['target_col'.pct_change()]
  • @CainãMaxCouto-Silva 我跑了 df["1 day percent change"] = df["1 day percent change".pct_change()] 并得到一个 AttributeError: 'str' object has no attribute ' pct_change'
  • @Jerome 刚刚做了 - 抱歉最初没有包含

标签: python pandas numpy csv


【解决方案1】:

代码块1中有误用pct_change:

x = df.pct_change()

您在竞争数据帧上使用 pct_change,而它是一个系列函数。 改为这样做:

x = df['close'].pct_change()
df["1 day percent change"] = x

然后是代码块 2 和 3,我不确定你想用什么来实现:

df[:,1:]

正确的语法是 iloc (df.iloc[:,1:])。但我不确定你想要实现什么,考虑到 np.diff 返回一个数组。 我的理解是代码块 1 可以达到您的预期。

【讨论】:

    【解决方案2】:

    您在尝试 1、2 和 3 中看到的错误是由于您的数据类型是对象 (str) 而不是数字 (float)。

    使用 df.dtypes 并且很可能您的数据类型都显示“close”和“adj close”等对象。

    df['close'] = df['close'].astype('float')
    df["1 day percent change"] = df['close'].pct_change()
    

    【讨论】:

      猜你喜欢
      • 2014-02-12
      • 2017-03-06
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      相关资源
      最近更新 更多