我一直在使用pandas库进行数据操作。在做下面的计算时,我被困在了某个地方。
我的excel文件中有下表,其中包含两列,我需要创建第三列(cap)。我需要使用python对程序中的第三列进行excel计算。
首先,我将创建下面的数据框DF,其中包含两列,我需要使用Python中的Excel公式在df中创建第三列。
数据帧(DF):-
Period rates
01-01-2021 0.0028
01-02-2021 0.0082
01-03-2021 0.0020
01-04-2021 0.0043
01-05-2021 0.0066
Excel表格:-
A B C
1 Period rates cap
2 01-01-2021 0.0028 =if(month(A2)=04,1,(1+$B3)*C3)
3 01-02-2021 0.0082 =if(month(A3)=04,1,(1+$B4)*C4)
4 01-03-2021 0.0020 =if(month(A4)=04,1,(1+$B5)*C5)
5 01-04-2021 0.0043 =if(month(A5)=04,1,(1+$B6)*C6)
6 01-05-2021 0.0066 =if(month(A6)=04,1,(1+$B7)*C7)
我刚刚创建了第三列(cap)来理解这个公式。我需要在我的python程序中这样做。
假设dataframe中的“period”列已经转换为datetime对象,那么只需定义自定义函数并使用df即可。apply()最有可能完成您的工作。
示例:(请正确更改自定义函数,因为我没有在下面的术语中包含乘以上限值)
import pandas as pd
df = pd.DataFrame({
'period': ['01-01-2021', '01-02-2021', '01-03-2021', '01-04-2021', '01-05-2021'],
'rates': [0.0028, 0.0082, 0.0020, 0.0043, 0.0066]
})
def cap_criteria(row):
if row['period'].month == 4:
return 1
else:
return (1 + row['rates'])
df['cap'] = df.apply(cap_criteria, axis=1)
print(df)
输出:
period rates cap
0 2021-01-01 0.0028 1.0028
1 2021-02-01 0.0082 1.0082
2 2021-03-01 0.0020 1.0020
3 2021-04-01 0.0043 1.0000
4 2021-05-01 0.0066 1.0066
如果“句点”列为字符串格式,则可以通过以下方式进行转换:
df['period'] = pd.to_datetime(df['period'], format='%d-%m-%Y')
或
df['period'] = pd.to_datetime(df['period'], format='%m-%d-%Y')
取决于您使用的日期约定。