首页 > 解决方案 > 如何处理具有多列和 if 语句的 Dataframe

问题描述

这是我的问题

您将在下面找到我的 DataFrame 示例:

df = pd.DataFrame({'Date':['01/03/2000','01/04/2000','01/05/2000','01/06/2000','01/07/2000','01/08/2000'],
                      'Paul_Score':[3,10,22,32,20,40],
                       'John_Score':[8,42,10,57,3,70]

                      })

df['Date']= pd.to_datetime(df['Date'])

df = df.set_index('Date')

我开始使用这样的 If 语句处理循环:

def test(selection,symbol):
    df_end = (selection*0)
    rolling_mean = selection.rolling(2).mean().fillna(0)
    calendar = pd.Series(df_end.index)

    for date in calendar:
        module=1/selection.loc[date,symbol]
        if  selection.loc[date,symbol] > rolling_mean.loc[date,symbol]:
            df_end.loc[date,symbol] = module

        else:
            df_end.loc[date,symbol]=0


    return df_end

然后 :

test(df,'John_Score')

但是,我的问题是我不知道如何同时处理许多列,我的目标是在整个数据帧(所有列)上尝试这个函数。这个示例只有 2 列,但实际上我有 30 列,我不知道该怎么做。

编辑 :

这就是我所拥有的test(df,'John_Score')

       Paul_Score John_Score
Date        
2000-01-03  0   0.125000
2000-01-04  0   0.023810
2000-01-05  0   0.000000
2000-01-06  0   0.017544
2000-01-07  0   0.000000
2000-01-08  0   0.014286

这就是我所拥有的test(df,'Paul_Score')

           Paul_Score John_Score
Date        
2000-01-03  0.333333    0
2000-01-04  0.100000    0
2000-01-05  0.045455    0
2000-01-06  0.031250    0
2000-01-07  0.000000    0
2000-01-08  0.025000    0

我想要这样的东西:

          Paul_Score John_Score
Date        
2000-01-03  0.333333    0.125000
2000-01-04  0.100000    0.023810
2000-01-05  0.045455    0.000000
2000-01-06  0.031250    0.017544
2000-01-07  0.000000    0.000000
2000-01-08  0.025000    0.014286

我的目标是每天检查 df 每一列,如果该值大于其滚动平均值 2 天的值,那么如果它为真,我们计算 df 的 1/值,如果不是,则计算 0。

它可能有一种更简单的方法,但我正在尝试提高我在 for/if 语句上的编码技能,我发现我在对具有多列的 Dataframes 进行计算时遇到了困难

如果您有任何想法,欢迎您

标签: pythonpandasloopsdataframeif-statement

解决方案


也许这段代码可以完成这项工作:

import pandas as pd

df = pd.DataFrame({'Date':['01/03/2000','01/04/2000','01/05/2000','01/06/2000','01/07/2000','01/08/2000'],
                      'Paul_Score':[3,10,22,32,20,40],
                       'John_Score':[8,42,10,57,3,70]

                      })

df['Date']= pd.to_datetime(df['Date'])

df = df.set_index('Date')

def test(selection,symbol):
    df_end = (selection*0)
    rolling_mean = selection.rolling(2).mean().fillna(0)
    calendar = pd.Series(df_end.index)

    for date in calendar:
        for cols in symbol:
            module=1/selection.loc[date,cols]
            if  selection.loc[date,cols] > rolling_mean.loc[date,cols]:
                df_end.loc[date,cols] = module

            else:
                df_end.loc[date,cols]=0


    return df_end

test(df,['Paul_Score', 'John_Score'])

输出:

            Paul_Score  John_Score
Date                              
2000-01-03    0.333333    0.125000
2000-01-04    0.100000    0.023810
2000-01-05    0.045455    0.000000
2000-01-06    0.031250    0.017544
2000-01-07    0.000000    0.000000
2000-01-08    0.025000    0.014286

推荐阅读