如何在python3中向数据帧中重复添加列

2024-05-16 14:17:15 发布

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

我正在写一个函数来模拟抛硬币游戏中的财富。f是我将把我的钱(资产管理规模)投入这个游戏的百分比。我模拟10000步,在每一步中,我都想把资产管理规模的数字加入我的财富列表,因此,在10000步结束时,我会有一个包含10001个数字的列表(包括资产管理规模=100)。最后,我想要一个数据帧(10001*100),每一列对应一个不同f(列名)的财富序列。但我下面的代码不断弹出错误:

raise TypeError(消息) TypeError:无法连接“”类型的对象;只有pd.Series、pd.DataFrame和pd.Panel(已弃用)对象才有效

或者

ValueError:值的长度与索引的长度不匹配

有人能帮我解决这个问题吗(在一个数据帧中添加100个系列,每个系列有10001个元素)?非常感谢

df = pd.DataFrame()
wealth = [100] ### initial AUM
def path(f): 
    global AUM
    global wealth
    for j in range(10000):  ### one simulation with 10,000 steps
        if Ber_Dist_V [j] == 1: ### Bernouli distribution
            AUM = AUM * (1-f) + AUM * f * (1 + win)
        else:
            AUM = AUM * (1-f) + AUM * f * (1 + lose)
        wealth.append(AUM)
    wealth = pd.Series(wealth)
    df[f]=wealth

weight = np.linspace(0, 1, 100,endpoint=False).tolist()
for f in weight:
    path_weight(f) 

Tags: 数据对象游戏dataframe列表数字资产series
1条回答
网友
1楼 · 发布于 2024-05-16 14:17:15

您得到的是ValueError,因为您的wealth列表的长度非常不同。实际上,没有必要将它转换为一个系列来将它设置为数据帧的一列。您的内部逻辑不是很透明,但是重置列表(因此wealth总是有一个恒定的长度)应该可以解决这个问题。我会建议类似于以下内容:

df = pd.DataFrame()
def path(f): 
    global AUM
    wealth = [100] # Resets `wealth` with each invocation of `path()`.
    for j in range(10000):  ### one simulation with 10,000 steps
        if Ber_Dist_V [j] == 1: ### Bernouli distribution
            AUM = AUM * (1-f) + AUM * f * (1 + win)
        else:
            AUM = AUM * (1-f) + AUM * f * (1 + lose)
        wealth.append(AUM)
    df[f] = wealth

weight = np.linspace(0, 1, 100,endpoint=False).tolist()
for f in weight:
    path_weight(f)

但是,如果您想使代码更快(而且您知道wealth的长度是l0001个元素,那么您可以在实例化时预先填充它,然后只更新元素。这应该比使用.append()快得多。我会这样写:

df = pd.DataFrame()
def path(f): 
    global AUM
    wealth = [100] + [0]*10000 # Resets `wealth` with each invocation of `path()`. Prefills wealth with `0`.
    for j in range(1, 10001):  ### one simulation with 10,000 steps
        if Ber_Dist_V [j] == 1: ### Bernouli distribution
            AUM = AUM * (1-f) + AUM * f * (1 + win)
        else:
            AUM = AUM * (1-f) + AUM * f * (1 + lose)
        wealth[i] = AUM    # Faster than using `.append()`.
    df[f] = wealth

weight = np.linspace(0, 1, 100,endpoint=False).tolist()
for f in weight:
    path_weight(f)

相关问题 更多 >