如何将迭代(从每个iter)结果附加到包含所有迭代结果的最终数据帧中?

2024-05-18 15:21:03 发布

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

我试图将计算矩阵的结果附加到我的df中。我对如何为计算设计迭代有一个问题。我有下面的代码,应该举例说明我正在尝试做什么。你知道吗

import pandas as pd
from pandas import DataFrame
import numpy as np

np_all = np.array([[1, 'vws.co', 1],
                    [1, 'nflx', 3],
                    [1, 'aapl', 2],
                    [2, 'vws.co', 1],
                    [2, 'nflx', 2],
                    [2, 'aapl', 1],
                    [3, 'vws.co', 1],
                    [3, 'nflx', 3],
                    [3, 'aapl', 1]])


df_all = pd.DataFrame(data=np_all, columns=['Date', 'Ticker', 'Close'])
df_all = df_all.sort(['Ticker','Date'], ascending=[1,1])

df_kpi_list = []
stocklist   = ['vws.co','nflx','aapl']

print (df_all)

def screener(df_all,ticker):

    # Copy df_all to df for single ticker operations
    df = df_all
    # filter to only relevant ticker
    df = df[df['Ticker'] == ticker]
    df = df[df.Ticker == ticker.lower()]


    def kpi1_calc(df,ticker):

        # do some KPI calculation that are appended to new columns of df
        pass

        def kpi2_calc(df,ticker):

            # do more KPI calculation that are appended to new columns of df
            pass

            def kpi3_calc(df,ticker):
                # example of more KPI calculation that are appended to new columns of df


                # Add content to df - RSI
                rsi = 3  # stupid example of a constant that is stored in df column
                r = rsi
                # add a RSI column
                r['RSI'] = rsi
                df_kpi_list.append(r)

                return df
            return df
        return df

    # concatenate all the ticker-iteration dfs from df_kpi_list into one df_all
    df_all = pd.concat(df_kpi_list)

    return df_all

if __name__ == '__main__':
    for ticker in stocklist:
        df_data = screener(df_all, ticker)

    print (df_data)

我有几层更复杂的数据:

  1. df\u kpi\u list=[]是一个空列表,特定于股票代码的df将附加到该列表中,因此我可以在最后将它们合并到一个新的包含所有df\u的列表中。你知道吗
  2. df\u all是一个包含所有我的股票信息的df(timeseries数据股票信息的多个股票信息)
  3. df相同的信息,但现在只过滤到相关的正在迭代的代码
  4. 上述df(pr ticker)将为每个kpi[no]\u calc函数添加更多信息并添加列-并且应添加到列表中:df\u kpi\u list=[]

什么是最聪明的方式来处理这些信息被计算,并最终总结成一个包罗万象的dfèu all?你知道吗


Tags: columnsofto信息dfnpalllist

热门问题