[Python] Pandas Overflow error converting date to month/year

Discussão em 'Python' iniciado por Stack, Abril 10, 2025.

  1. Stack

    Stack Membro Participativo

    I'm doing the following problem on Leetcode: https://leetcode.com/problems/monthly-transactions-i/

    My question doesn't deal much with the actual problem, all you need to know is that there is a column 'trans_date' that has dates in the YYYY-MM-DD format, and I'd like to convert this date to the YYYY-MM format.

    But, if I write:

    import pandas as pd

    def monthly_transactions(transactions: pd.DataFrame) -> pd.DataFrame:
    transactions['trans_date'] = transactions['trans_date'].dt.to_period('M')
    return transactions


    I get a Runtime error when running on Leetcode:

    OverflowError: Maximum recursion level reached
    return ujson_dumps(
    Line 263 in write (/usr/local/lib/python3.10/dist-packages/pandas/io/json/_json.py)
    ).write()
    Line 210 in to_json (/usr/local/lib/python3.10/dist-packages/pandas/io/json/_json.py)
    return json.to_json(
    Line 2702 in to_json (/usr/local/lib/python3.10/dist-packages/pandas/core/generic.py)
    return func(*args, **kwargs)
    Line 333 in wrapper (/usr/local/lib/python3.10/dist-packages/pandas/util/_decorators.py)
    json_file = simplejson.loads(result_table.to_json(orient='split'))
    Line 48 in main (_driver.py)
    main()
    Line 62 in <module> (_driver.py)


    But, this is fine (it runs and gives the wrong answer):

    import pandas as pd

    def monthly_transactions(transactions: pd.DataFrame) -> pd.DataFrame:
    transactions['trans_date'].dt.to_period('M')
    return transactions


    I'm pretty confused here, since running this on my own computer and not through Leetcode is fine.

    Can anyone else reproduce this behavior and/or suggest how to fix it?

    Continue reading...

Compartilhe esta Página