【问题标题】:How to find max Amount per month (for the year)如何找到每月的最大金额(一年)
【发布时间】:2019-05-28 07:26:37
【问题描述】:

我刚开始使用 Pandas 和 Python。我有我银行的年度交易的 CSV 转储文件。每个纳税季节,我都需要准备一份报告,报告每个月(和特定日期)达到的最大值以及总体最大值:

样本数据:

df = pd.DataFrame(data={'Date': ['2018-01-01','2018-01-05', '2018-05-01'],
                        'Transaction': ['CREDIT', 'DEBIT', 'CREDIT'],
                         'Amount': [100.20, -50.00, 200.00]})

我不知道如何在内联 DataFrame 上使用 pd.to_datetime。

试过df['Date'].apply(pd.to_datetime)但出错了

ValueError: ('Unknown string format:', 'CREDIT', '发生在索引 #交易')

df = pd.read_csv("~/Downloads/cheq.csv", parse_dates=[0], na_values="n/a")
df = pd.DataFrame(data, columns=['Date', 'Transaction', 'Amount'])
df.set_index(['Date'], drop=True, inplace=True)

grouped = df.groupby(pd.Grouper(freq="M"))  # DataFrameGroupBy (grouped by Month)

for g, v in grouped:
   print(g, v.max())

输出:

2018-01-31 00:00:00 Transaction     DEBIT
Amount         100.02
dtype: object
2018-02-28 00:00:00 Transaction    CREDIT
Amount            200
dtype: object

我希望看到的是(某种形式的):

2018-01-01 00:00:00 Transaction     DEBIT
Amount         100.02
2018-02-01 00:00:00 Transaction    CREDIT
Amount            200

感谢您的帮助。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您已转换日期格式,然后应用 groupBy。 试试这个!

    df = pd.DataFrame(data={'Date': ['2018-01-01','2018-01-05', '2018-05-01'],
                 'Transaction': ['CREDIT', 'DEBIT', 'CREDIT'],
                 'Amount': [100.20, -50.00, 200.00]})
    df['Date'] = pd.to_datetime(df['Date'])
    print(df.groupby(df['Date'].dt.strftime('%B')).max())
    
    #output:
             Amount       Date Transaction
    Date                                  
    January   100.2 2018-01-05       DEBIT
    May       200.0 2018-05-01      CREDIT
    

    【讨论】:

    • 快到了!我将如何添加日期,而不仅仅是月份?例如。 1 月 2 日、5 月 1 日等?
    • 只需在 strftime 中添加 %d。请找到我更新的解决方案
    • 这给了我两个条目,但我只想要每月的最大值,所以这似乎工作:print(df.groupby(df['Date'].dt.strftime('%B'))['Date', 'Amount', 'Transaction'].max())`日期金额交易`DateFebruary 2018-02-01 200.0 CREDITJanuary 2018-01-05 100.2 DEBIT
    • 你想要每个月的最大日期是吗?
    • 非常感谢@AI_Learning。我已经在这里待了4个多小时。我现在明白了……为什么在数据科学中使用 Python。你,先生。岩石。祝您新年快乐!
    猜你喜欢
    • 2013-07-02
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 2021-01-19
    • 2020-07-26
    • 1970-01-01
    相关资源
    最近更新 更多