基于选定数据帧列和值的计算函数

2024-06-27 09:23:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据if语句计算一个结果,如下所述。不知怎的,我只收到楠,不明白为什么

import pandas as pd

def Calculation(values6M, values6M3M):

    Calc = (values6M/(values6M3M/1000))          
    return Calc

df = pd.DataFrame([
        ['A', '6M3M', '1Y', 3.25],
        ['A', '6M3M', '2Y', 3.25],
        ['A', '6M3M', '3Y', 3.25],
        ['A', '6M3M', '4Y', 3.375],
        ['A', '6M3M', '5Y', 3.5],
        ['B', '6M', '1Y', 0.1475],
        ['B', '6M', '2Y', 0.15],
        ['B', '6M', '3Y', 0.155],
        ['B', '6M', '4Y', 0.18],
        ['B', '6M', '5Y', 0.21875],
        ['A', '3M', '1Y', 0.1113],
        ['A', '3M', '2Y', 0.1138],
        ['A', '3M', '3Y', 0.115],
        ['A', '3M', '4Y', 0.1175],
        ['A', '3M', '5Y', 0.1188]        
        ], columns=['Type', 'Course', 'Course_Period', 'Values'])

for index, row in df.iterrows():
    if row['Type'] in ['A', 'B'] and row['Course'] in ['6M', '6M3M']:

        test6M = df.loc[df['Course'] == '6M']        
        test6M3M = df.loc[df['Course'] == '6M3M']

        result = Calculation(test6M,test6M3M)
        print(result)

我想要的结果是第一个值

1Y: 0.1475/(3.25/1000) = 45.38461538

2Y: 46.15384615
3Y: 47.69230769
4Y: 53.33333333
5Y: 62.5

Tags: indfiftypecalcresultlocrow
2条回答

您可以使用isin作为过滤器,使用groupby+pct_change得到比率:-)

(df.loc[df.Type.isin(['A','B'])&df.Course.isin(['6M', '6M3M'])].groupby('Course_Period').pct_change()+1).dropna()*1000
Out[294]: 
      Values
5  45.384615
6  46.153846
7  47.692308
8  53.333333
9  62.500000

这是一种方法,如果您想查看输入,这种方法很方便

df2 = pd.pivot_table(df, index=['Course_Period'],
                     columns=['Type', 'Course'], values=['Values']).reset_index()

df2.columns = df2.columns = [' '.join(col).strip() for col in df2.columns.values]

df2['Result'] = df2['Values B 6M'] / df2['Values A 6M3M'] * 1000

#   Course_Period  Values A 3M  Values A 6M3M  Values B 6M     Result
# 0            1Y       0.1113          3.250      0.14750  45.384615
# 1            2Y       0.1138          3.250      0.15000  46.153846
# 2            3Y       0.1150          3.250      0.15500  47.692308
# 3            4Y       0.1175          3.375      0.18000  53.333333
# 4            5Y       0.1188          3.500      0.21875  62.500000

相关问题 更多 >