【问题标题】:Python: for loop iterations when adding dataframesPython:添加数据帧时的for循环迭代
【发布时间】:2021-09-12 15:21:21
【问题描述】:

我有一个具有不同返回值的数据框,如下所示:

0.2  -0.1  0.03  0.01
0.02  0.1  -0.1  -0.2
0.05  0.06  0.07 -0.07
0.03 -0.04 -0.04 -0.03

我有一个单独的数据框,索引仅在一列中返回:

0.01
0.015
-0.01
-0.02

我想要做的是基本上将索引返回数据帧的每一行值与股票返回数据帧中每一列的每个值相加(+)。

期望的结果如下:

0.21  -0.09
0.035  0.115
0.04   0.05
0.01  -0.06 etc etc

例如,在 Matlab 中,for 循环通常非常简单,但在 python 中,索引是让我陷入困境的原因。 我尝试了一个简单的 for 循环:

for i, j in df_stock_returns.iterrows():
    df_new = df_stock_returns[i, j] + df_index_reuturns[j] 

但这并不真正起作用,感谢任何帮助!

【问题讨论】:

  • 如果把后者做成numpy数组,可以直接添加,没有对齐问题df1 + df2.to_numpy()

标签: python pandas numpy loops


【解决方案1】:

您可以简单地添加两个df,如下所示

col1=[0.2,0.02]
col2=[-0.1,0.2]
col3=[0.01,0.015]
df1=pd.DataFrame(data=list(zip(col1, col2)),columns=['list1','list2'])
df2=pd.DataFrame({'list3':col3})

output = df1[:] + df2['list3'].values

df1[:] 提取所有列并将其提取到引用列df2['list3']

【讨论】:

    【解决方案2】:

    假设你有

    In [27]: df
    Out[27]: 
          0     1     2     3
    0  0.20 -0.10  0.03  0.01
    1  0.02  0.10 -0.10 -0.20
    2  0.05  0.06  0.07 -0.07
    3  0.03 -0.04 -0.04 -0.03
    

    In [28]: dfi
    Out[28]: 
           0
    0  0.010
    1  0.015
    2 -0.010
    3 -0.020
    

    你可以写

    In [26]: pd.concat([df[c] + dfi[0] for c in df], axis=1)
    Out[26]: 
           0      0      1      2
    0  0.210 -0.090  0.040  0.020
    1  0.035  0.115 -0.085 -0.185
    2  0.040  0.050  0.060 -0.080
    3  0.010 -0.060 -0.060 -0.050
    

    在 pandas 中,您几乎不需要遍历单个单元格。在这里,我只是对列进行了迭代,df[c] + dfi[0] 按元素添加了两列。然后 concataxis=1 (0=rows, 1=columns) 只是将所有内容连接到一个数据帧中。

    【讨论】:

      【解决方案3】:

      我想最直接的方法会奏效

      for c in a.columns:
          a[c] = a[c] + b
      
      >>> a
             0      1      2      3
      0  0.210 -0.090  0.040  0.020
      1  0.215 -0.085  0.045  0.025
      2  0.190 -0.110  0.020  0.000
      3  0.180 -0.120  0.010 -0.010
      

      【讨论】:

        猜你喜欢
        • 2019-11-10
        • 1970-01-01
        • 2012-06-27
        • 2023-03-05
        • 1970-01-01
        • 1970-01-01
        • 2022-06-23
        • 2016-01-18
        • 1970-01-01
        相关资源
        最近更新 更多