【发布时间】:2020-06-04 08:16:19
【问题描述】:
这个脚本的目的是:
• 读取一组 csv 文件。
• 刮掉日期并从中提取一些特征。
• 将这些 csv 文件合并到一个数据框中。
• 将最终数据框导入另一个类并打印。
代码如下:
import pandas as pd
import os
class DataSource:
def __init__(self):
self.dfs = []
self.final = pd.DataFrame()
self.names = ['Date', 'Time', 'open', 'high', 'low', 'close', 'Volume']
self.directory = os.chdir(r"C:\Users\Sayed\Desktop\forex")
def merge(self):
for file in os.listdir(self.directory):
df = pd.read_csv(file, names=self.names,
parse_dates={'Release Date': ['Date', 'Time']})
self.dfs.append(df)
self.final = pd.concat(self.dfs, axis=0)
self.final = self.final[['Release Date', 'open', 'high', 'low', 'close']]
print(self.final.head())
return self.final
class test():
def __init__(self):
self.df = DataSource.final
def print(self):
return print(self.df.head())
x = test()
x.print()
这是错误:
Traceback(最近一次通话最后一次):
文件“C:/Users/Sayed/PycharmProjects/project/hello.py”,第 31 行,在 x = 测试()
init 中的文件“C:/Users/Sayed/PycharmProjects/project/hello.py”,第 26 行 self.df = DataSource.final
AttributeError: type object 'DataSource' has no attribute 'final'
【问题讨论】:
-
是的,
final是一个实例属性,而不是类属性。DataSource().final例如可以工作…… -
您尚未初始化数据源实例。
final属于一个实例,而不是类。 (它在init内)因此,如果不初始化Datasource的实例,就无法访问final。也就是说,我不知道你想用test类实现什么。