首页 > 解决方案 > 熊猫,每行数据帧的多次计算

问题描述

我有以下数据框:

df = pd.DataFrame({'date': ['31/12/2015','31/12/2016','31/12/2017','31/12/2018',
                            '31/12/2019','31/12/2020','31/12/2015','31/12/2016',
                            '31/12/2017','31/12/2018','31/12/2019','31/12/2020'], 
                   'season': ['S1','S1','S1','S1','S1','S1','S2','S2','S2','S2','S2','S2'], 
                   'total' : [1,0,0,0,0.022313421,0.053791041,0,0,0.307783314,0,0,0] })
df.date=  pd.to_datetime(df.date)
print(df)  

         date season         total
0  2015-12-31     S1      1.000000
1  2016-12-31     S1      0.000000
2  2017-12-31     S1      0.000000
3  2018-12-31     S1      0.000000
4  2019-12-31     S1      0.022313
5  2020-12-31     S1      0.053791
6  2015-12-31     S2      0.000000
7  2016-12-31     S2      0.000000
8  2017-12-31     S2      0.307783
9  2018-12-31     S2      0.000000
10 2019-12-31     S2      0.000000
11 2020-12-31     S2      0.000000

我想根据“总计”列中包含的值对每一行进行几次计算,以获得以下格式的数据框(第一行的示例):

         date season         total   calculation id       result
0  2015-12-31     S1      1.000000                1           x1
0  2015-12-31     S1      1.000000                2           x2
0  2015-12-31     S1      1.000000                3           x3  
0  2015-12-31     S1      1.000000                4           x4
0  2015-12-31     S1      1.000000                5           x5   

基本上是这样的:

for index, row in df.iterrows():
    for i, a in enumerate(np.linspace(0,getattr(row,'total'),6)):
          assing the result of the calculation to the column result

关于我该怎么做的任何想法?出于示例的目的,可以 a*5在循环中评估结果列。

谢谢你的帮助,

皮埃尔

标签: pythonpandasiterationrows

解决方案


完成这项工作并“复制”行的一种方法是首先为 df 中的每一行创建一个列 list_results:

df['list_result'] = df['total'].apply(lambda a: np.linspace(0,a,6)*5)

在此列中,您可以使用stack为列表中的每个值创建一个包含一行的系列,并且通过首先设置索引,您可以直接在系列上工作:

df_output = (df.set_index(['date', 'season','total'])['list_result'] 
               # set index and work on the column list_result
                 .apply(pd.Series).stack() #will expand the lists of results as rows
                 .reset_index()) # to get back the column 'date', 'season','total'
#you can rename the column
df_output.columns = ['date', 'season','total', 'calculation_id', 'result']

df_output 的第一行是:

         date season     total  calculation_id    result
0  2015-12-31     S1  1.000000               0  0.000000
1  2015-12-31     S1  1.000000               1  1.000000
2  2015-12-31     S1  1.000000               2  2.000000
3  2015-12-31     S1  1.000000               3  3.000000
4  2015-12-31     S1  1.000000               4  4.000000
5  2015-12-31     S1  1.000000               5  5.000000

请注意,这并不是您期望的结果,但通过使用np.linspace(0,getattr(row,'total'),6)它会得到您将得到的结果,然后您可以在创建 list_result 时更改此函数。


推荐阅读