gpt4 book ai didi

python - 将列表转换为数据框/调整一行循环

转载 作者:行者123 更新时间:2023-12-01 06:31:36 25 4
gpt4 key购买 nike

我正在获取一个返回数据框,其中每列都衡量一个时间范围内的返回百分比。接下来我计算累计返回如下:

return_cuml = [np.cumprod(return[column]+1 用于返回中的列]

但是,这会将累积 yield 输出为一个列表,其中每个元素都是一系列 yield 。我的原始数据框包含以下列:Portfolio、Benchmark、100_0、50_50、70_30 等。

如何修复一行 for 循环或将新列表转换为与以前具有相同列名的数据框?

代码

import random
import pandas as pd
import numpy as np
random.seed(321)

port = []
bmk = []
eq = []
ff = []
idk = []

for i in range(10):
port.append(random.randrange(-100,100,1)/100)
bmk.append(random.randrange(-100,100,1)/100)
eq.append(random.randrange(-100,100,1)/100)
ff.append(random.randrange(-100,100,1)/100)
idk.append(random.randrange(-100,100,1)/100)

frame = {'Portfolio': port, 'Benchmark':bmk, '100_0':eq, '50_50':ff, '70_30':idk}
df = pd.DataFrame(frame)
df_cuml = [(np.cumprod(df[column]+1)*10000) for column in df]
np.cumprod(df['100_0']+1)*10000

** 预期输出

port = np.cumprod(df['Portfolio']+1)*10000
bmk = np.cumprod(df['Benchmark']+1)*10000
eq = np.cumprod(df['100_0']+1)*10000
ff = np.cumprod(df['50_50']+1)*10000
idk = np.cumprod(df['70_30']+1)*10000
frame = {'Portfolio': port, 'Benchmark':bmk, '100_0':eq, '50_50':ff, '70_30':idk}
expected_output = pd.DataFrame(frame)
print(expected_output)

最佳答案

尝试apply :

df.apply(lambda x: np.cumprod(x + 1) * 10000)

或者使用 concatseries 列表转换为 Dataframe (related topic):

df_cuml = [(np.cumprod(df[column]+1)*10000) for column in df]

df_cuml = pd.concat(df_cuml, axis=1, keys=[s.name for s in df_cuml])
print(df_cuml)
# Portfolio Benchmark 100_0 50_50 70_30
# 0 7000.000000 10000.000000 3200.000000 9500.000000 14300.000000
# 1 7910.000000 8700.000000 5888.000000 5890.000000 22022.000000
# 2 9175.600000 9396.000000 11599.360000 10013.000000 23783.760000
# 3 10643.696000 5355.720000 347.980800 19525.350000 30918.888000
# 4 6811.965440 5891.292000 27.838464 19330.096500 45759.954240
# 5 8514.956800 2886.733080 6.124462 10824.854040 24252.775747
# 6 8004.059392 5282.721536 6.736908 18077.506247 31771.136229
# 7 6963.531671 1056.544307 4.311621 20427.582059 59094.313386
# 8 6406.449137 1827.821652 2.069578 37586.750988 83913.925008
# 9 6406.449137 1114.971207 2.856018 7141.482688 79718.228757

关于python - 将列表转换为数据框/调整一行循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59883664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com