【发布时间】:2018-09-06 04:43:49
【问题描述】:
Pandas 新手,如果有明显的解决方案,我很抱歉... 我导入了一个只有 2 列的 CSV,并创建了第 3 列。 这是前 10 行和标题的屏幕截图: Screen shot of DataFrame
我已经弄清楚如何在 ['Amount Changed'] 列中找到最小值和最大值,但还需要提取与最小值和最大值相关的日期 - 但不是索引和 ['Profit/Loss' ]。我已经尝试过 iloc、loc、阅读有关 groupby 的信息 - 我无法让它们中的任何一个返回我可以再次使用的单个值(在本例中为日期)。
我的目标是创建一个新变量“Gi_Date”,它与 ['Amount Changed'] 中的最大值位于同一行,但与 ['Date'] 列中的日期相关联。
我试图将变量分开,以便我可以在打印语句中使用它们,将它们写入 txt 文件等。
import os
import csv
import pandas as pd
import numpy as np
#path for CSV file
csvpath = ("budget_data.csv")
#Read CSV into Panadas and give it a variable name Bank_pd
Bank_pd = pd.read_csv(csvpath, parse_dates=True)
#Number of month records in the CSV
Months = Bank_pd["Date"].count()
#Total amount of money captured in the data converted to currency
Total_Funds = '${:.0f}'.format(Bank_pd["Profit/Losses"].sum())
#Determine the amount of increase or decrease from the previous month
AmtChange = Bank_pd["Profit/Losses"].diff()
Bank_pd["Amount Changed"] = AmtChange
#Identify the greatest positive change
GreatestIncrease = '${:.0f}'.format(Bank_pd["Amount Changed"].max())
Gi_Date = Bank_pd[Bank_pd["Date"] == GreatestIncrease]
#Identify the greatest negative change
GreatestDecrease = '${:.0f}'.format(Bank_pd["Amount Changed"].min())
Gd_Date = Bank_pd[Bank_pd['Date'] == GreatestDecrease]
print(f"Total Months: {Months}")
print(f"Total: {Total_Funds}")
print(f"Greatest Increase in Profits: {Gi_Date} ({GreatestIncrease})")
print(f"Greatest Decrease in Profits: {Gd_Date} ({GreatestDecrease})")
当我在 git bash 中运行脚本时,我不再收到错误,所以我想我已经接近了,而不是显示它说的日期:
$ python PyBank.py
Total Months: 86
Total: $38382578
Greatest Increase in Profits: Empty DataFrame
Columns: [Date, Profit/Losses, Amount Changed]
Index: [] ($1926159)
Greatest Decrease in Profits: Empty DataFrame
Columns: [Date, Profit/Losses, Amount Changed]
Index: [] ($-2196167)
我希望它像这样打印出来:
$ python PyBank.py
Total Months: 86
Total: $38382578
Greatest Increase in Profits: Feb-2012 ($1926159)
Greatest Decrease in Profits: Sept-2013 ($-2196167)
这是原始 DataFrame 一年的价值:
bank_pd = pd.DataFrame({'Date':['Jan-10', 'Feb-10', 'Mar-10', 'Apl-10', 'May-10', 'Jun-10', 'Jul-10', 'Aug-10', 'Sep-10', 'Oct-10', 'Nov-10', 'Dec-10'],
'Profit/Losses':[867884, 984655, 322013, -69417, 310503, 522857, 1033096, 604885, -216386, 477532, 893810, -80353]})
样本 df 的预期输出为: 总月数:12 总资金:5651079 美元 利润增幅最大:10 月 10 日(693918 美元) 利润降幅最大:12 月 10 日 ($-974163)
我在上面的示例数据框中也有一个错误,当我快速输入时我错过了一个月 - 现在已修复。
谢谢!
【问题讨论】:
-
请发布您当前的数据框和您预期的输出数据框
-
@pyd - 这是我正在使用的数据框的示例。我没有发布预期的结果数据框,因为我真正想要的是如何从数据框中识别出可以在其他地方使用的值,即打印到 txt 文件...谢谢!
-
你不能只做
df.sort_values('Profit/Losses').tail(1).Date的最大日期并将尾部从最小日期更改为head吗?? -
@Dave,请给我们给定数据子集的预期输出
-
@Dave 你可以只取出日期的值而不是把它们放回数据框中
标签: python-3.x pandas