【问题标题】:How to add the date in a for loop without if/else statements如何在没有 if/else 语句的情况下在 for 循环中添加日期
【发布时间】:2019-06-18 00:04:12
【问题描述】:

我的任务是创建一个 Python 脚本来分析我的 pybank.csv 中的记录以计算以下各项: https://i.stack.imgur.com/MzM4N.png

数据集中包含的总月数 整个期间“盈亏”的净总额 整个期间“盈亏”变化的平均值 整个期间的最大利润增长(日期和金额) 整个期间损失的最大减少(日期和金额)

Expected Results: 

Financial Analysis
----------------------------
Total Months: 86
Total: $38382578
Average  Change: $-2315.12
Greatest Increase in Profits: Feb-2012 ($1926159)
Greatest Decrease in Profits: Sep-2013 ($-2196167)

我无法添加具体日期。

我尝试了嵌套 for 循环、numpy 库和子...

import statistics 
import numpy as np

df = pd.read_csv("./pybank.csv")

f = open('results.txt','w+')

numMonths = df['Date'].count()
profit = df['Profit/Losses'].sum()
increaseProfit = df['Profit/Losses'].max()

profitLossesList = list(df['Profit/Losses'])
dateProfitLossesList = df['Date']

changeList = []
counter = 0

numDB = np.array(profitLossesList)
dateNp = np.array(dateProfitLossesList)
date = ""

for i in range(len(df)-1):
    curr = profitLossesList[i]
    currDown = profitLossesList[i+1]
    changeList.append(currDown-curr)
    counter = sum(df['Profit/Losses'])
    minChange = min(changeList)
    maxChange = max(changeList)  
    avgChance = round(np.mean(changeList),2)








#Escribimos en el documento results.txt los resultados
f.write(f"Financial Analysis\n----------------------------------\n")
f.write(f"Your profit is: ${profit}\n")
f.write(f"Total Months {numMonths}\n")
f.write(f"Average  Change: ${avgChance}\n")
f.write(f"Greatest Increase in Profits: (${maxChange})\n")
f.write(f"Greatest Decrease in Profits: (${minChange})\n")

print(f"\nFinancial Analysis\n----------------------------------\n")
print(f"Your profit is: ${profit}")
print(f"Total Months {numMonths}")
print(f"Average  Change: ${avgChance}")
print(f"Greatest Increase in Profits: (${maxChange})")
print(f"Greatest Decrease in Profits: (${minChange})")



#Cerramos documento
f.close()
Actual Results: 

Financial Analysis
----------------------------------

Your profit is: $38382578
Total Months 86
Average  Change: $-2315.12
Greatest Increase in Profits: ($1926159)
Greatest Decrease in Profits: ($-2196167)```



【问题讨论】:

    标签: python pandas csv numpy


    【解决方案1】:

    试试这个以获得最大变化月份:

    maxChangeMonth = dateProfitLossesList[changeList.index(max(changeList))]

    对于 min 只需在 max 函数中替换。

    【讨论】:

      猜你喜欢
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多