Python:if语句中的行级计算

2024-06-08 10:03:47 发布

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

我试图根据数据内部的条件(年、月和金额)创建索引(重复字段)。例如:

^{tb1}$

我试图创建的逻辑是:

If the current row of Year is equal the previous row of Year then check 
if the current row of Amount is equal to previous row of Amount if it is true 
check if the previous row of Month is not equal to the current row of Month-1, 
if it is true then 1 else use the previous value of Recurring+1, everything else 1. 
Follows below a simple formula that runs on Excel: 
   =IF(A2=A1,IF(C2=C1,IF(B1<>(B2-1),1,D1+1),1),1)

下面是我试图在Python中运行的代码:

for i in range(1, len(df_pivoted)):
    if df.loc[i+1 ,'Year'] == df.loc[i ,'Year']:
        if df.loc[i+1 , 'amount'] == df_.loc[i , 'amount']:
            if df.loc[i , 'Month'] != df.loc[(i+1)-1 , 'Month']:
                df.loc[i, 'Recurring'] = 1
            else:
                    df.loc[i, 'Recurring'] = df.loc[i+1, 'Recurring']
        else:
                df.loc[i, 'Recurring'] = 1
    else:
            df.loc[i, 'Recurring'] = 1

有人能帮我吗?我是python新手,我不知道该怎么做才能让它正常工作。 问候


Tags: ofthedfifisequalcurrentyear
1条回答
网友
1楼 · 发布于 2024-06-08 10:03:47

如果我正确理解了你的问题,这就是你需要的:

df.at[0, "Recurring"] = 1
for index in df.index[1:]:
    if df.at[index, "Year"] == df.at[index-1, "Year"] and df.at[index, "Amount"] == df.at[index-1, "Amount"] and df.at[index, "Month"] == df.at[index-1, "Month"]+1:
        df.at[index, "Recurring"] = df.at[index-1, "Recurring"]+1
    else:
        df.at[index, "Recurring"] = 1

相关问题 更多 >