将列表转换为数据帧/为循环调整一行

2024-04-29 08:15:57 发布

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

我采用的是一个收益数据框架,其中每一列衡量一个时间范围内的收益百分比。接下来,我将按如下方式计算累积回报:

return_cuml = [np.cumprod(return[column]+1 for column in returns]

但是,这会将累积回报输出为一个列表,其中每个元素都是一系列回报。我的原始数据框架有很多列,如:公文包、基准、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)

Tags: indfforportnpcolumnrandomframe
1条回答
网友
1楼 · 发布于 2024-04-29 08:15:57

试试^{}

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

或者使用concatrelated topic)将series列表转换为Dataframe

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

相关问题 更多 >