【问题标题】:Is there a decent way to compute iterative value in dataframe?有没有一种体面的方法来计算数据框中的迭代值?
【发布时间】:2020-04-28 03:01:54
【问题描述】:

我有两个数据框看起来像:

   col1  
0  1     

   col2  
0  2
1  3
2  4
3  5
4  6  

我的目标是使用 col2 中的数字填充 col1:

   col1      col2
0  1          2
1  2(=1x2)    3   
2  6(=2x3)    4
3  24(=6x4)   5
4  102(=24x5) 6 

因此,col1 中的数字计算为上一行 col1 中的值与上一行 col2 中的值的乘积。

【问题讨论】:

  • 这个问题很相似,应该让你朝着正确的方向前进:stackoverflow.com/questions/34855859/…
  • @Bubblethan 如果您可以将任何满意的答案标记为正确,那就太好了。如果您仍需要一些说明,请随时询问。

标签: python pandas


【解决方案1】:

如果性能很重要,我认为numba 是在这里使用循环的方式:

@jit(nopython=True)
def func(a, b):
    res = np.empty(a.shape)
    res[0] = b
    for i in range(1, a.shape[0]):
        res[i] = res[i-1] * a[i-1]
    return res

df2['col1'] = func(df2['col2'].values, df1.loc[0, 'col1'])

print (df2)
   col2   col1
0     2    1.0
1     3    2.0
2     4    6.0
3     5   24.0
4     6  120.0

【讨论】:

    【解决方案2】:

    您可以在这里使用移位和累积乘积,无需迭代,如下所示:

    import pandas as pd
    
    # Lets create artificial data
    df_1 = pd.DataFrame() 
    df_2 = pd.DataFrame() 
    
    df_1['col_1'] = [1]
    df_2['col_2'] = [2,3,4,5,6]
    
    # Now lets add col_1 to df_2 
    df_2['col_1'] = df_1['col_1']
    
    # And fill all nans in the way you want
    df_2['col_1'].fillna(df_2['col_2'].shift(1).cumprod(), inplace = True)
    

    【讨论】:

      【解决方案3】:
      for i in range(1,len(df2)):
          df1.at[i,'col1'] = df1.col1[i-1] * df2.col2[i-1]
      
      df1['col2'] = df2.col2
      
      >>> df1
          col1  col2
      0    1.0     2
      1    2.0     3
      2    6.0     4
      3   24.0     5
      4  120.0     6
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-06
        • 2023-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-21
        • 1970-01-01
        相关资源
        最近更新 更多