利用Python實現簡單的Excel統計函數

需求分析

根據原始數據,計算出累計和、回撤、連續正確、連續錯誤、連續正確值與連續錯誤值6項數據,其中原始數據大於等於0認定為正確,原始數據小於0為錯誤。明白瞭要求,那我們就開始擼代碼吧~

解決步驟

import pandas as pd
#創建一個計算數據的函數
def calculate(df):
  pass
#讀取原始數據,將索引列去除
df = pd.read_excel('需求0621.xlsx',index_col=0)
#調用計算數據的函數
calculate(df)

先把整體思路寫好,再去想辦法計算每項數據

#計算累計和
    lst1 = []
    sum = 0
    for i in range(df.shape[0]):
        if i == 0:
            lst1.append(df['N'][i])
            sum += df['N'][i]
        else:
            sum += df['N'][i]
            lst1.append(sum)
    df['累計和'] = lst1
#計算回撤
    lst2 = []
    max = 0
    for i in range(df.shape[0]):
        if i == 0:
            lst2.append(0)
        elif df['累計和'][i] > max:
            max = df['累計和'][i]
            lst2.append(0)
        elif df['累計和'][i] < max:
            lst2.append(df['累計和'][i]-max)
        elif df['累計和'][i] == max:
            lst2.append(0)
    df['回撤'] = lst2
#計算連續正確的個數
    lst3 = []
    correct = 0
    for i in range(df.shape[0]):
        if df['N'][i] >= 0:
            correct += 1
            lst3.append(correct)
        else:
            lst3.append(0)
            correct = 0
    df['連續正確'] = lst3
#計算連續錯誤的個數
    lst4 = []
    mistake = 0
    for i in range(df.shape[0]):
        if df['N'][i] < 0:
            mistake += 1
            lst4.append(mistake)
        else:
            lst4.append(0)
            mistake = 0
    df['連續錯誤'] = lst4
#計算連續正確值
    lst5 = []
    for i in range(df.shape[0]):
        lst5.append('')
    right = 0
    for i in range(df.shape[0]):
        if df['連續正確'][i] != 0:
            right += df['N'][i]
        elif df['連續正確'][i] == 0 and right != 0:
            lst5[i-1] = right
            right = 0
    df['連續正確值'] = lst5
#計算連續錯誤值
    lst6 = []
    for i in range(df.shape[0]):
        lst6.append('')
    wrong = 0
    for i in range(df.shape[0]):
        if df['連續錯誤'][i] != 0:
            wrong += df['N'][i]
        elif df['連續錯誤'][i] == 0 and wrong != 0:
            lst6[i-1] = wrong
            wrong = 0
    df['連續錯誤值'] = lst6

最後將dataframe保存到excel

    df.to_excel('完成計算.xlsx')
    print('保持成功')

最終結果

技術總結

雖然已經完成瞭要求計算出瞭所有的數據,但在寫代碼過程中計算的步驟都是基於python基礎語法實現的,對於pandas的使用還要隻有通過大量的練習才能夠熟練的掌握

到此這篇關於利用Python實現簡單的Excel統計函數的文章就介紹到這瞭,更多相關Python實現Excel統計函數內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: