Home > database >  Adding a dictionary to a row in a Pandas DataFrame using concat in Python 3.10
Adding a dictionary to a row in a Pandas DataFrame using concat in Python 3.10

Time:03-22

After updating to Python 3.10, I now receive the following warning when using frame.append to append a dictionary to a Pandas DataFrame.

FutureWarning: The frame.append method is deprecated and will be
removed from pandas in a future version. Use pandas.concat instead.

Below is the code. This still works, though I would like to resolve the warning.

report = report.append({
                "period":period,
                "symbol":symbol,
                "start_date":start_date,
                "start_price":start_price,
                "start_market_cap":start_market_cap,
                "end_date":end_date,
                "end_price":end_price,
                "end_market_cap":end_market_cap,
                "return":return_
            },ignore_index=True)

I have updated the code to the below, which kicks a different warning:

report = pd.concat([report,{
                "period":period,
                "symbol":symbol,
                "start_date":start_date,
                "start_price":start_price,
                "start_market_cap":start_market_cap,
                "end_date":end_date,
                "end_price":end_price,
                "end_market_cap":end_market_cap,
                "return":return_
            }],ignore_index=True)

TypeError: cannot concatenate object of type '<class 'dict'>'; only Series and DataFrame objs are valid

2 questions: Is the first warning wrong? What is the 3.10 way to achieve this? Thanks.

CodePudding user response:

Use loc to assign a single row value:

report.loc[len(report)] = {"period":period,
                           "symbol":symbol,
                           "start_date":start_date,
                           "start_price":start_price,
                           "start_market_cap":start_market_cap,
                           "end_date":end_date,
                           "end_price":end_price,
                           "end_market_cap":end_market_cap,
                           "return":return_
                          }
  • Related