多个for循环可创建熊猫数据框

时间:2018-10-13 09:31:37

标签: python pandas for-loop

我正在尝试创建一个如下所示的熊猫数据框:

          -5      0      5
index                     
-5       NaN  slope  slope
 0     slope    NaN  slope
 5     slope  slope    NaN

但我能得到的最接近的代码是下面的代码,该代码返回仅包含一列的数据帧(这是从ctr1循环到最后一次迭代的列表)

weather = np.linspace(-5, 5, 3)

for ctr1 in weather:
    slope_list = []
    X1 = round(ctr1,1)
    for ctr2 in weather:
        X2 = round(ctr2,1)

        Y1 = regressor[0] * X1**3 + \
        regressor[1] * X1**2 + \
        regressor[2] * X1 + \
        regressor[3] 

        Y2 = regressor[0] * X2**3 + \
        regressor[1] * X2**2 + \
        regressor[2] * X2 + \
        regressor[3]

        slope = (Y2-Y1)/(X2-X1)
        slope_list.append(slope)

    df_final = pd.DataFrame({X1:slope_list})

有人可以帮忙吗?

4 个答案:

答案 0 :(得分:2)

df_final仅获得3个元素,因为它与for ctr2 in weather处于相同的缩进级别,因此它在每个外部循环中都得到重新分配。尽管,如果您对此进行了修复,则将获得只有一个长列的数据框:只有一个slope_list附加到该数据框的末尾将变成一个数据框。

这是我无需更改分配方法即可解决的方法:

weather = np.linspace(-5, 5, 3)
slope_list = []
for ctr1 in weather:
X1 = round(ctr1,1)
for ctr2 in weather:
    X2 = round(ctr2,1)

    Y1 = regressor[0] * X1**3 + \
    regressor[1] * X1**2 + \
    regressor[2] * X1 + \
    regressor[3] 

    Y2 = regressor[0] * X2**3 + \
    regressor[1] * X2**2 + \
    regressor[2] * X2 + \
    regressor[3]

    slope = (Y2-Y1)/(X2-X1)
    slope_list.append(slope)


#make it 3 columns and 3 rows as intended
slope_list = np.array(slope_list).reshape(3, 3)
#make the dataframe
df_final = pd.DataFrame({X1:slope_list})
#manually add the desired row and column indexes
df_final = df.set_index(weather)
df_final.columns = weather

尽管您应该记住,除非您确切地知道自己在做什么,否则在处理熊猫时制作循环和嵌套循环通常意味着您会错过一种更轻松,更好的处理方法。

答案 1 :(得分:1)

您可以尝试直接在DataFrame中分配值。只需使用index = weather创建空的DataFrame:

<div class="body"></div>
<div class="grad"></div>
<div class="col-xs-4">
    <div class="header">
        <div><b>Bienvenue sur<span>qUIZZ CERI</span><b></div>
    </div>
</div>
<br>
<form class="col-xs-8" method="get" action="/login">
    <div class="login">
        <input type="text" placeholder="username"name="username"><br>
        <input type="password" placeholder="password"name="password"><br>
        <input type="submit" value="Login">
    </div>
</form>

答案 2 :(得分:0)

slope_list = []会在每次迭代时重置结果列表,因此仅保留最后一个。您需要在外部循环之外定义结果列表,并将子结果附加到该结果列表中。

答案 3 :(得分:0)

如上所述,为了完整性,我发布了我的问题的答案,该问题适用于更大的天气范围。唯一的区别是我在代码的前面做了四舍五入:

weather = np.round(np.linspace(-5, 35, 401), decimals = 1)
df_final = pd.DataFrame([], index=weather)
for ctr1 in weather:
    X1 = ctr1
    for ctr2 in weather:
        X2 = ctr2

        Y1 = regressor[0] * X1**3 + \
        regressor[1] * X1**2 + \
        regressor[2] * X1 + \
        regressor[3] 

        Y2 = regressor[0] * X2**3 + \
        regressor[1] * X2**2 + \
        regressor[2] * X2 + \
        regressor[3]

        slope = (Y2-Y1)/(X2-X1)

        df_final.loc[X1, X2] = np.NaN if X1 == X2 else slope