合并2+个不同长度的列valueerror:值的长度

esyap4oy  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(159)

我正在尝试创建一个Dataframe main_df 哪些有索引 date 然后是 df['high']-df['low'] 从每个股票行情。
注:在这个例子中,3个股票数据从1996年1月1日到2020年12月31日。acn于2001/07/19上市
因此,长度 df['high']-df['low'] 会有所不同。
我使用的代码如下:

import pandas as pd

def test_demo():
    tickers = ['ADI', 'ACN', 'ABT']
    df2 = pd.DataFrame()
    main_df = pd.DataFrame()
    pd.set_option('display.max_columns', None)
    for count, ticker in enumerate(tickers):
        df = pd.read_csv('demo\{}.csv'.format(ticker))
        print(df)
        df = df.set_index('date')
        df2['date'] = df.index
        df2 = df2.set_index('date')
        df2[ticker] = df['high'] - df['low']

        if main_df.empty:
            main_df = df2
            count = 1
        else:
            main_df = main_df.join(df2, on='date', how='outer')
            # main_df = main_df.merge(df, on='date')
            # print(main_df)
        if count % 10 == 0:
            print(count)
    main_df.to_csv('testdemo.csv')

test_demo()

它给了我一个错误和回溯如下

Traceback (most recent call last):
  File "D:\PycharmProjects\backtraderP1\Main.py", line 81, in <module>
    from zfunctions.WebDemo import test_demo
  File "D:\PycharmProjects\backtraderP1\zfunctions\WebDemo.py", line 33, in <module>
    test_demo()
  File "D:\PycharmProjects\backtraderP1\zfunctions\WebDemo.py", line 13, in test_demo
    df2['date'] = df.index
  File "C:\Users\Cornerstone\AppData\Roaming\Python\Python39\site-packages\pandas\core\frame.py", line 3163, in __setitem__
    self._set_item(key, value)
  File "C:\Users\Cornerstone\AppData\Roaming\Python\Python39\site-packages\pandas\core\frame.py", line 3242, in _set_item
    value = self._sanitize_column(key, value)
  File "C:\Users\Cornerstone\AppData\Roaming\Python\Python39\site-packages\pandas\core\frame.py", line 3899, in _sanitize_column
    value = sanitize_index(value, self.index)
  File "C:\Users\Cornerstone\AppData\Roaming\Python\Python39\site-packages\pandas\core\internals\construction.py", line 751, in sanitize_index
    raise ValueError(
ValueError: Length of values (4895) does not match length of index (6295)

Process finished with exit code 1

代码通过第一次处理adi,得到acn数据时出现错误。线路 df2['date'] = df.index 以及 df2[ticker] = df['high'] - df['low'] 应该不是问题。并出现在其他帖子的答案中。但这种组合在这种情况下不起作用。如果有人能帮我理解并解决这个问题,那就太好了。非常感谢。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题