在python中向数据帧添加列

2024-10-04 05:26:17 发布

您现在位置:Python中文网/ 问答频道 /正文

如何循环浏览excel表并将每个“调整后的接近”添加到数据框中?我想总结一下所有的调整收盘价并做一个股票指数。你知道吗

当我尝试使用下面的代码时,数据帧百分比变化为空。你知道吗

xls = pd.ExcelFile('databas.xlsx')
countSheets = len(xls.sheet_names)

Percent_Change = pd.DataFrame()

x = 0
for x in range(countSheets):
    data = pd.read_excel('databas.xlsx', sheet_name=x, index_col='Date')

    # Calculate the percent change from day to day
    Percent_Change[x] = pd.Series(data['Adj Close'].pct_change()*100,     index=Percent_Change.index)


 stock_index = data['Percent_Change'].cumsum()

Tags: 数据dataindexxlsxxlschangeexcelsheet
1条回答
网友
1楼 · 发布于 2024-10-04 05:26:17

不幸的是,我没有数据来复制您的完整示例。但是,您的代码中似乎有一个bug。 在“x”上循环,“x”是一个整数列表。您可能希望循环处理工作表名称并将它们附加到DF中。如果您想这样做,您的代码应该是:

import pandas as pd

xls = pd.ExcelFile('databas.xlsx')
# pep8 unto thyself only, it is conventional to use "_" instead of camelCase or to avoid longer names if at all possible
sheets = xls.sheet_names

Percent_Change = pd.DataFrame()

# using sheet instead of x is more "pythonic"
for sheet in sheets:
    data = pd.read_excel('databas.xlsx', sheet_name=sheet, index_col='Date')

    # Calculate the percent change from day to day
    Percent_Change[sheet] = pd.Series(data['Adj Close'].pct_change()*100, index=Percent_Change.index)

stock_index = data['Percent_Change'].cumsum()

相关问题 更多 >