Python 3.x 在数据框中,查找最大值并返回相邻列的值,而不是整行

Python 3.x 在数据框中,查找最大值并返回相邻列的值,而不是整行,python-3.x,pandas,Python 3.x,Pandas,熊猫是新手,所以如果有一个明显的解决办法,我很抱歉。。。 我导入了一个只有两列的CSV,并创建了第三列。 以下是前10行和标题的屏幕截图: 我已经知道如何在['Amount Changed']列中找到最小值和最大值,但还需要提取与最小值和最大值关联的日期,而不是索引和['Profit/Loss']。我试过iloc,loc,读过关于groupby的文章-我不能让它们中的任何一个返回一个我可以再次使用的值(在本例中是一个日期) 我的目标是创建一个新变量'Gi_Date',该变量与['Amount

熊猫是新手,所以如果有一个明显的解决办法,我很抱歉。。。 我导入了一个只有两列的CSV,并创建了第三列。 以下是前10行和标题的屏幕截图:

我已经知道如何在['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)
以下是原始数据帧的一年价值:

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 = pd.DataFrame({'Date':['Jan-2010', 'Feb-2010', 'Mar-2010', 'Apr-2010', 'May-2010',
                           'Jun-2010', 'Jul-2010', 'Aug-2010', 'Sep-2010', 'Oct-2010'],
                   'Profit/Losses': [867884,984655,322013,-69417,310503,522857,
                                     1033096,604885,-216386,477532]})
df['Amount Changed'] = df['Profit/Losses'].diff()

print(df)

       Date  Profit/Losses  Amount Changed
0  Jan-2010         867884             NaN
1  Feb-2010         984655        116771.0
2  Mar-2010         322013       -662642.0
3  Apr-2010         -69417       -391430.0
4  May-2010         310503        379920.0
5  Jun-2010         522857        212354.0
6  Jul-2010        1033096        510239.0
7  Aug-2010         604885       -428211.0
8  Sep-2010        -216386       -821271.0
9  Oct-2010         477532        693918.0

print(df.loc[df['Amount Changed'].idxmin(), 'Date'])
print(df.loc[df['Amount Changed'].idxmax(), 'Date'])

Sep-2010
Oct-2010
样本df的预期输出为: 总月份:12 资金总额:5651079美元 利润增幅最大:2010年10月(693918美元) 利润最大跌幅:2010年12月(974163美元)

我在上面的示例数据框中也出现了一个错误,当我快速打印出来时,我错过了一个月,现在已经修复了


谢谢

我发现使用的变量中没有什么小故障

Bank_pd["Amount Changed"] = AmtChange
上面的语句实际上是用列“amountchanged”替换数据框。在此语句之后,您可以使用此列进行任何操作

下面是更新的代码,并突出显示了新添加的行。您可以添加进一步的格式:

import pandas as pd


csvpath = ("budget_data.csv")

Bank_pd = pd.read_csv(csvpath, parse_dates=True)
inp_bank_pd = pd.DataFrame(Bank_pd)

Months = Bank_pd["Date"].count()
Total_Funds = '${:.0f}'.format(Bank_pd["Profit/Losses"].sum())

AmtChange = Bank_pd["Profit/Losses"].diff()
GreatestIncrease = Bank_pd["Amount Changed"].max()

Gi_Date = inp_bank_pd.loc[Bank_pd["Amount Changed"] == GreatestIncrease]

print(Months)
print(Total_Funds)
print(Gi_Date['Date'].values[0])
print(GreatestIncrease)
print("Total Months: %s" %(Months))
print("Total: %s" %(Total_Funds))
print("Greatest Increase in Profits: %s %s" %(Gi_Date.to_string(index=False), GreatestIncrease))
print("Greatest Decrease in Profits: %s %s" %(Gd_Date.to_string(index=False), GreatestDecrease))

在您的示例代码中,Gi_date和Gd_date尝试初始化新的DF,而不是调用值。更改Gi_日期和Gd_日期:

Gi_Date = Bank_pd.sort_values('Profit/Losses').tail(1).Date
Gd_Date = Bank_pd.sort_values('Profit/Losses').head(1).Date
检查输出:

Gi_Date
Jul-10
Gd_Date
Sep-10
要打印使用字符串格式的打印方式,请执行以下操作:

import pandas as pd


csvpath = ("budget_data.csv")

Bank_pd = pd.read_csv(csvpath, parse_dates=True)
inp_bank_pd = pd.DataFrame(Bank_pd)

Months = Bank_pd["Date"].count()
Total_Funds = '${:.0f}'.format(Bank_pd["Profit/Losses"].sum())

AmtChange = Bank_pd["Profit/Losses"].diff()
GreatestIncrease = Bank_pd["Amount Changed"].max()

Gi_Date = inp_bank_pd.loc[Bank_pd["Amount Changed"] == GreatestIncrease]

print(Months)
print(Total_Funds)
print(Gi_Date['Date'].values[0])
print(GreatestIncrease)
print("Total Months: %s" %(Months))
print("Total: %s" %(Total_Funds))
print("Greatest Increase in Profits: %s %s" %(Gi_Date.to_string(index=False), GreatestIncrease))
print("Greatest Decrease in Profits: %s %s" %(Gd_Date.to_string(index=False), GreatestDecrease))
注意,如果您不使用:

(Gd_Date.to_string(index=False)
熊猫对象信息将包含在打印输出中,就像您看到DataFrame信息时的示例一样。 12个月样本DF的输出:

Total Months: 12
Total: $5651079
Greatest Increase in Profits: Jul-10 $693918
Greatest Decrease in Profits: Sep-10 $-974163

Series.idxmin
Series.idxmax
loc
一起使用:

df.loc[df['Amount Changed'].idxmin(), 'Date']
df.loc[df['Amount Changed'].idxmax(), 'Date']
基于示例数据帧的完整示例:

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 = pd.DataFrame({'Date':['Jan-2010', 'Feb-2010', 'Mar-2010', 'Apr-2010', 'May-2010',
                           'Jun-2010', 'Jul-2010', 'Aug-2010', 'Sep-2010', 'Oct-2010'],
                   'Profit/Losses': [867884,984655,322013,-69417,310503,522857,
                                     1033096,604885,-216386,477532]})
df['Amount Changed'] = df['Profit/Losses'].diff()

print(df)

       Date  Profit/Losses  Amount Changed
0  Jan-2010         867884             NaN
1  Feb-2010         984655        116771.0
2  Mar-2010         322013       -662642.0
3  Apr-2010         -69417       -391430.0
4  May-2010         310503        379920.0
5  Jun-2010         522857        212354.0
6  Jul-2010        1033096        510239.0
7  Aug-2010         604885       -428211.0
8  Sep-2010        -216386       -821271.0
9  Oct-2010         477532        693918.0

print(df.loc[df['Amount Changed'].idxmin(), 'Date'])
print(df.loc[df['Amount Changed'].idxmax(), 'Date'])

Sep-2010
Oct-2010

请发布当前数据帧和预期输出dataframe@pyd-这是我正在使用的数据帧示例。我没有发布预期的结果数据框,因为我真正想要的是如何从数据框中识别出一个可以在其他地方使用的值,即打印到txt文件。。。谢谢你不能只做
df.sort_values('proit/loss').tail(1).Date
作为最长日期,并将tail从最短日期改为
head
。@Dave请给我们提供你的数据子集的预期输出data@Dave你只需要取出日期的值,而不是把它们放回DataFrame。这让我非常接近!谢谢我做了一些小改动,但仍然有一个小错误。我将这些值与('Amount Changed')最小值和最大值进行匹配,因此第一个月(1月-10日)在该列中没有值。然后我把gd…头(2)改为跳过1月份,让它打印10月10日,这正是我所期待的。现在奇怪的是,它正在打印10月10日至1月10日的693918美元。我只是想知道如何摆脱1月10日,它是完美的!head()不是在做你想的事。它指的是要选择的值的数量,而不是值的位置。Head()也不是基于0的,因为Head(1)选择第一行。头(2)选择前2行,等等。如果您想让我今天晚些时候看一下,我很乐意这样做!如果你对接受的答案感到满意,我就让它去吧。谢谢你的澄清和帮助。另外两个解决方案对我很有效,所以你不需要在这一个上花费更多的时间。我很好奇头和尾是如何工作的,如果有办法跳过X行以供将来参考。。。谢谢-谢谢你的建议!我一直得到一个索引错误:索引0超出了大小为0的轴0的界限。不过我会继续玩它,我需要熟悉loc功能!我花了一段时间才让它起作用,出于某种原因,我唯一能让它起作用的方法就是与银行合作。据我所知,该行向df添加了一个新列,并在每一行中运行AmtChange公式。谢谢-非常感谢@Nihal和Vijay的帮助!!这也奏效了!我真的很欣赏带有loc示例的idxmax!