将函数应用于 Pandas 数据框并获取结果作为新数据框

问题描述 投票:0回答:1

我有这个代码:

import yfinance as yF
import datetime
import pandas as pd

df = pd.DataFrame({'ID':['1', '2'], 'Ticker': ['AIN', 'TILE'], 'Company':['Albany International', 'Interface']})


def get_returns(tic,com):
    df_Stock = yF.download(tickers = tic, period = "max", interval = "1mo", prepost = False, repair = False)
    df_Stock[com + ' % Growth'] = df_Stock['High']-df_Stock['Open']
    df_Stock[com + ' % Growth'] = (df_Stock[com + ' % Growth'] * 100 )/df_Stock['Open']
    
    return df_Stock[com + ' % Growth']

get_returns('AIN','AIN')

到目前为止,一切都按预期进行。

df1 = df.apply(lambda x: get_returns(x.Ticker, x.Company), axis=1)

这里我尝试使用这个功能

get_returns()

将 Pandas apply 和 lambda 应用于上面定义的数据框 df 上。所需的输出是另一个数据帧 df1,它有 3 列

  1. 日期
  2. 公司 1 - 奥尔巴尼国际 % 回报
  3. 公司 2 - 接口退货百分比

如果数据框 df 中有更多行,则每个公司将成为 df1 中的一个新列,其每月回报将是“日期”列下给定时间段的行值。

python pandas dataframe apply
1个回答
0
投票

这是我为以下数据框运行代码时得到的输出

身份证 股票代码 公司
0 1 艾恩 奥尔巴尼国际
1 2 瓷砖 界面

输出

日期 1985-01-01 1985-02-01 1985-03-01 1985-04-01 1985-05-01 1985-06-01 1985-07-01 1985-08-01 1985-09-01 1985-10-01 ... 2023-01-01 2023-02-01 2023-03-01 2023-04-01 2023-05-01 2023-06-01 2023-07-01 2023-08-01 2023-09-01 2023-10-01
0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... 13.081953 3.767988 1.609221 3.527832 3.188085 11.953453 5.196635 0.891469 1.352506 0.290596
1 inf inf inf inf inf inf inf inf inf inf ... 15.577892 8.091470 5.604387 1.231532 2.809710 27.745666 12.328766 8.771934 3.567984 1.530608

我相信您正在运行的代码会为原始数据框中的每个索引创建一个条目。 因此第 0 行对应于“AIN”,第 1 行对应于“TILE”。

要将其转换为所需的格式,您需要转置 df1 并根据 df 重命名列。

df1 = df1.T
df1.rename(columns=df['Company'] + ' % Returns', inplace=True)

输出:

日期 奥尔巴尼国际退货百分比 接口%回报
1985-01-01 NaN inf
1985-02-01 NaN inf
1985-03-01 NaN inf
1985-04-01 NaN inf
1985-05-01 NaN inf
... ... ...
2023-06-01 11.953453 27.745666
2023-07-01 5.196635 12.328766
2023-08-01 0.891469 8.771934
2023-09-01 1.352506 3.567984
2023-10-01 0.290596 1.530608
© www.soinside.com 2019 - 2024. All rights reserved.