代码之家  ›  专栏  ›  技术社区  ›  Unnikrishnan

无法在Jupyter笔记本单元中再次加入熊猫数据帧

  •  0
  • Unnikrishnan  · 技术社区  · 7 年前

    我要加两个新的 SMA 列到我的数据帧,使用 pandas.DataFrame.join 功能。

    第一次运行正常,但如果再次运行该单元,将收到以下错误:

    ValueError: columns overlap but no suffix specified: Index(['SMA_LONG'], dtype='object')

    以下是我的代码。

    #cell 1
    import numpy as np
    import pandas as pd
    
    #cell 2
    df = pd.DataFrame({
       'close': np.random.uniform(0.1,0.9, 100),
    })
    
    #cell 3
    SMA_long = 12
    SMA_short = 7
    sma_long = df['close'].rolling(window=SMA_long, min_periods=SMA_long - 1).mean()
    df = df.join(sma_long.to_frame('SMA_LONG'))
    
    sma_short = df['close'].rolling(window=SMA_short, min_periods=SMA_short - 1).mean()
    df = df.join(sma_short.to_frame('SMA_SHORT'))
    
    df.tail()
    

    我怎么能解决这个问题?

    谢谢。

    1 回复  |  直到 7 年前
        1
  •  1
  •   jezrael    7 年前

    你的错误意味着已经 SMA_LONG 之前 df = df.join(sma_long.to_frame('SMA_LONG')) .


    对于我来说,您的示例数据解决方案工作得很好,但我认为您可以通过分配给新列来简化它:

    SMA_long = 12
    SMA_short = 7
    df['SMA_LONG'] = df['close'].rolling(window=SMA_long, min_periods=SMA_long - 1).mean()
    df['SMA_SHORT'] = df['close'].rolling(window=SMA_short, min_periods=SMA_short - 1).mean()
    
    print (df)
           close  SMA_LONG  SMA_SHORT
    0   0.649439       NaN        NaN
    1   0.332926       NaN        NaN
    2   0.492527       NaN        NaN
    3   0.500444       NaN        NaN
    4   0.583334       NaN        NaN
    ..       ...       ...        ...
    95  0.775169  0.532850   0.577613
    96  0.470479  0.524123   0.594733
    97  0.237417  0.517054   0.512506
    98  0.753701  0.536595   0.554372
    99  0.133795  0.526603   0.475595
    
    [100 rows x 3 columns]
    

    或:

    sma_long = df['close'].rolling(window=SMA_long, min_periods=SMA_long - 1).mean()
    sma_short = df['close'].rolling(window=SMA_short, min_periods=SMA_short - 1).mean()
    
    df = df.assign(SMA_LONG=sma_long, SMA_SHORT=sma_short)