繁体   English   中英

基于所选数据框列和值的计算功能

[英]Calculation function based on selected dataframe columns and values

我想根据if语句计算结果,如下所述。 不知何故,我只收到NaN,却不明白为什么?

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

您可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM