How can I use pandas concat instead of pandas append now it is depreciating?

Viewed 1774

I have an empty dataframe and I want to loop over an API call and input data into it based on the stock symbol in my spreadsheet.

final_dataframe = final_dataframe.append(
        pd.Series(
        [
            symbol,
            data[symbol]['price'],
            data[symbol]['stats']['year1ChangePercent'], 
            'N/A'
        ],
        index = my_columns),
            ignore_index = True
        )

As above, I currently use the append method to add the data to my dataframe, but as append is depreciating in pandas 1.4.0, I want to know how to re write the above using concat. I current have this but it does not work:

final_dataframe = pd.concat([final_dataframe,
        pd.Series(
        [
            symbol,
            data[symbol]['price'],
            data[symbol]['stats']['year1ChangePercent'], 
            'N/A'
        ],
        index = my_columns),
            ignore_index = True
                                    ])
2 Answers

Not sure concat supports concatenating a DataFrame with a Series so maybe try .to_frame(), and I've also moved a closing bracket:

final_dataframe = pd.concat([final_dataframe,
    pd.Series(
    [
        symbol,
        data[symbol]['price'],
        data[symbol]['stats']['year1ChangePercent'], 
        'N/A'
    ],
    index = my_columns).to_frame()],
        ignore_index = True
                                )

Using .loc is another option.

Replace pd.Series with pd.DataFrame:

final_dataframe = pd.concat([final_dataframe, pd.DataFrame({
     final_dataframe.columns[0]: [symbol],
     final_dataframe.columns[1]: [data[symbol]['price']],
     final_dataframe.columns[2]: [data[symbol]['stats']['year1ChangePercent']],
     final_dataframe.columns[3]: ['N/A']})], ignore_index=True)
Related