基于某些输入参数的新列以选择要使用的列-Python

时间:2019-01-04 18:40:40

标签: python python-3.x pandas

具有一个熊猫数据框,其中包含多列每月财务数据。我输入的是运行程序的人指定的时间段。目前,它只是保存为句点,如下面的代码所示。

#coded into python
period = ?? (user adds this in from input screen)

我需要创建另一列数据,使用输入的期间号来计算其他列。

enter image description here

因此,在上表中,我想创建一个新的列“计算”,该列取决于期间输入。例如,如果使用时段1,则将完成以下calc1(实际上完成了数学运算)。期间= 2-然后是calc2。期间= 3-然后是calc3。我只需要根据期间数计算出一列,但是在下图中添加了三个示例来说明其工作方式。

enter image description here

我可以在用例时用SQL做到这一点。因此,使用输入时间段,然后求和我需要的列。

select  Account #,
'&Period' AS Period,                    
'&Year' AS YR,                  
case                    
  When '&Period' = '1' then sum(d_cf+d_1)                   
  when '&Period' = '2' then sum(d_cf+d_1+d_2)                   
  when '&Period' = '3' then sum(d_cf+d_1+d_2+d_3)                   

我不确定如何在python(新手学习者)中轻松地做到这一点。是的,我可以创建一个列,在每个可能的时间段(1-12)内通过新列进行每次计算,然后仅选择该列,但我想学习并以一种更有效的方式进行操作。

您能提供更多帮助或为我指明更好的方向吗?

3 个答案:

答案 0 :(得分:1)

您可以使用python中的一个简单函数来做到这一点:

def get_calculation(df, period=NULL): 

    '''
    df = pandas data frame
    period = integer type
    '''

    if period == 1:
        return df.apply(lambda x: x['d_0'] +x['d_1'], axis=1)

    if period == 2:
        return df.apply(lambda x: x['d_0'] +x['d_1']+ x['d_2'], axis=1)

    if period == 3:
        return df.apply(lambda x: x['d_0'] +x['d_1']+ x['d_2'] + x['d_3'], axis=1)

new_df = get_calculation(df, period = 1)

设置:

df = pd.DataFrame({'d_0':list(range(1,7)),
                   'd_1': list(range(10,70,10)),
                   'd_2':list(range(100,700,100)),
                   'd_3': list(range(1000,7000,1000))})

答案 1 :(得分:1)

您当然可以做类似的事情

df[['d_cf'] + [f'd_{i}' for i in range(1, period+1)]].sum(axis=1)

答案 2 :(得分:1)

设置:

import pandas as pd

ddict = {
    'Year':['2018','2018','2018','2018','2018',],
    'Account_Num':['1111','1122','1133','1144','1155'],
    'd_cf':['1','2','3','4','5'],
    }

data = pd.DataFrame(ddict)

创建价值计算器:

def get_calcs(period):
    # Convert period to integer
    s = str(period)

    # Convert to string value
    n = int(period) + 1

    # This will repeat the period number by the value of the period number
    return ''.join([i * n for i in s])

主函数复制数据帧,循环访问周期值,并将计算值设置为每个相关列的索引正确的点:

def process_data(data_frame=data, period_column='d_cf'):
    # Copy data_frame argument
    df = data_frame.copy(deep=True)

    # Run through each value in our period column
    for i in df[period_column].values.tolist():

        # Create a temporary column
        new_column = 'd_{}'.format(i)

        # Pass the period into our calculator; Capture the result
        calculated_value = get_calcs(i)

        # Create a new column based on our period number
        df[new_column] = ''

        # Use indexing to place the calculated value into our desired location
        df.loc[df[period_column] == i, new_column] = calculated_value

    # Return the result
    return df

开始:

   Year Account_Num d_cf
0  2018        1111    1
1  2018        1122    2
2  2018        1133    3
3  2018        1144    4
4  2018        1155    5

结果:

process_data(data)

   Year Account_Num d_cf d_1  d_2   d_3    d_4     d_5
0  2018        1111    1  11                          
1  2018        1122    2      222                     
2  2018        1133    3           3333               
3  2018        1144    4                 44444        
4  2018        1155    5                        555555