熊猫数据框,找到最大值并返回相邻列的值,而不是整行

时间:2018-09-06 04:43:49

标签: python-3.x pandas

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) 利润下降幅度最大:2010年12月(-974163美元)

上面的示例数据框中也有一个错误,当我快速键入它时,我错过了一个月-现在已修复。

谢谢!

3 个答案:

答案 0 :(得分:3)

我发现所使用的变量很少出现毛病。

Bank_pd["Amount Changed"] = AmtChange

上面的语句实际上是用“金额更改”列替换数据框。声明之后,您可以使用此列进行任何操作。

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

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)

答案 1 :(得分:1)

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

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

要使用字符串格式打印要打印的方式:

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

答案 2 :(得分:1)

Series.idxminSeries.idxmaxloc一起使用:

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

基于示例DataFrame的完整示例:

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