python - 查找多个 DataFrame Python 中数字的最大值

标签 python python-3.x pandas numpy finance

我有 1000 多个包含股票日期和价格的 .txt 文件,我已将它们转换为字典(以文件名(股票代码)作为键,每个文件的数据作为数据框)。我使用 .rolling 计算了移动平均线,然后找到了移动平均线与价格之间的百分比差异。因此,百分比差异是每个 DataFrame 自己的列。所有这些的代码如下所示:

filelist = os.listdir(r'Insert File Path')
filepath = r'Insert File Path'


dic1 = {}

for file in filelist:
    df = pd.read_csv(filepath + file,sep='\t')
dic1[file]= df

for value in dic1.values():
    value.rename(columns={value.columns[0]:'Dates',value.columns[1]:'Prices'},inplace=True)

for value in dic1.values():
    value['ma'] = value['Prices'].rolling(window=50).mean()

for value in dic1.values():
    value['diff'] = value['Prices'] - value['ma']

for value in dic1.values():
     value['pctdiff']= value['diff']/value['Prices']

我的问题是如何找到 pctdiff 列中前 5 个最大(也是最小,因为它们可能为负)的列?

我已经尝试过:

for df in dic1.values():
    for num in df['pctdiff'].max():
        print(num.max())

但我收到以下错误:“'float'对象不可迭代”

最佳答案

你是这个意思吗?

list_result = []
for key,value in dic1.items():
    value.rename(columns={value.columns[0]:'Dates',value.columns[1]:'Prices'},inplace=True)
    value['ma'] = value['Prices'].rolling(window=50).mean()
    value['diff'] = value['Prices'] - value['ma']
    value['pctdiff']= value['diff']/value['Prices']
    list_result.append([key,value['pctdiff'].max()])

list_result.sort(key = lambda x : x[1] )
highest_list = list_result[-5:]
smallest_list = list_result[:5]

关于python - 查找多个 DataFrame Python 中数字的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60256628/

相关文章:

python - PyInstaller 构建的 Windows EXE 因 multiprocessing.pool 而失败

python - 这个返回或设置变量的代码可以变得更简单吗?

python-3.x - python : finding elements of a webpage to scrape in python when page content is loaded using Java script

python - 通过 Pandas 对重复项进行分组并组合字符串列

python - Pandas 用空白/空字符串替换 NaN

python - 从生成器广播标签数据时出现问题

python - 如何加快 Pandas 的重采样过程?

python - python-flask处理应用程序错误

python - pandas:按组插入一个空白行和一行带索引的行?

python - file.readines() 之后的 split() 出错