【问题标题】:Pandas concat axis 1 failing(infinite loading)Pandas concat 轴 1 失败(无限加载)
【发布时间】:2022-01-24 14:02:57
【问题描述】:

我正在尝试连接 csv 文件和 MA_3、MA_5 列(它们有 NAN)。 csv 文件 = https://drive.google.com/file/d/1-219dqlmhFA6-YtD8xRigo_ZVoAIJ21v/view?usp=sharing

代码是这样的。


df = pd.read_csv('/content/mydrive/MyDrive/data/005930.KS.csv')

MA_3, MA_5  = pd.Series([]), pd.Series([])


for i, adj_close in enumerate(df['Adj Close']):
  MA_3 = MA_3.append(pd.Series([pd.Series.mean(ds['Adj Close'][i:i+3])]))
  MA_5 = MA_5.append(pd.Series([pd.Series.mean(ds['Adj Close'][i:i+5])]))
MA_3 = pd.concat([pd.DataFrame({'MA3':['','']}), MA_3.to_frame('MA3').iloc[:-2,:]])
MA_5 = pd.concat([pd.DataFrame({'MA5':['','','','']}), MA_5.to_frame('MA5').iloc[:-4,:]])
MA = pd.concat([MA_3, MA_5], axis=1, ignore_index=True)
df = pd.concat([df, MA], axis=1, ignore_index=True)

MA_3.shape 与 MA_5.shape 相同,但不起作用。它不会引发错误,但会发生无限加载。(axis = 0 确实有效。)我想解决这个问题。谢谢。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    测试你的代码我得到一个InvalidIndexError: Reindexing only valid with uniquely valued Index objects 错误(没有无限加载)。 由于MA_3MA_5 数据帧的索引不是唯一的,因此发生错误。您可以在 concat 操作之前简单地重置索引:

    MA_3.reset_index(drop=True, inplace=True)
    MA_5.reset_index(drop=True, inplace=True)
    MA = pd.concat([MA_3, MA_5], axis=1, ignore_index=True)
    

    设置了选项drop=True,因此旧索引(在这种情况下不需要)不会作为新列添加。

    注意:如果我理解正确,您的目标是在您的数据框中添加运行平均值为 Adj Close 的两列。实现此目的的更简单方法是使用 pandas rolling 函数:

    df = pd.read_csv(in_dir + file)
    df['MA_3'] = df['Adj Close'].rolling(window=3).mean()
    df['MA_5'] = df['Adj Close'].rolling(window=5).mean()
    

    注 2:上面我假设它是 for 循环中的 df['Adj Close'][i:i+3](不是 ds['Adj Close'][i:i+3],下一行相同)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      • 2021-09-16
      • 1970-01-01
      • 2020-05-24
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多