首页 > 解决方案 > 根据不同数据框中的值创建新数据框

问题描述

我正在尝试根据数据框前一列中的值和另一个数据框的值创建附加数据框。

我正在处理的问题要求我在 100 个时间段内为 50 个人生成一个从 0 到 1 的随机数。每个人都从位置 x=0 开始,并有可能在 x=0 和 x=1 之间来回移动。如果他们在那个时期产生的数量大于 0.9,他们就会切换位置(所以如果他们在上一个时期在 x=0,他们将移动到 x=1;如果他们在上一个时期在 x=1,他们将移动到 x=0)。如果该数字不大于 0.9,则它们停留在与前一个时间段相同的位置。我试图找到每个人在每个时间段的位置。

这是我到目前为止所拥有的:

#First I generated a 50x100 dataframe of random numbers
rv = pd.DataFrame(np.random.uniform(low = 0.0, high = 1.0, size=(51, 100)), columns = range(1,101))
#print(rv)

#Next, I created a new dataframe that tells me whether the value in the random number dataframe is greater than 0.9
rv_2 = rv[rv > 0.9].notnull()
#rv_2

#this is where I am stuck right now
#First I made a dataframe where every individual starts at location x=0 
rv_3 = pd.DataFrame(0, index = range(51), columns = range(1))

#Here I am trying to append the location of each individual for each time period
#I was trying to add a 1 in the rv_3 dataframe if the previous column had a 0 and the corresponding value in the rv_2 dataframe was true, and so on
for col in rv_2:
    for i, row_value in rv_2[col].iteritems():
        if rv_2[col][i] == True & rv_3[col][i-1] == 0:
            rv_3[col][i] = 1
        elif rv_2[col][i] == True & rv_3[col][i-1] == 1:
            rv_3[col][i] = 1
        else:
            rv_3[col][i] = rv_3[col][i-1]

先感谢您!

标签: pythonpandasloopsnumpydataframe

解决方案


推荐阅读