Apply function to multiple dataframes and create multiple dataframes from that


I have a list of multiple data frames on cryptocurrency. So I want to apply a function to all of these data frames, which should convert all the data frames so that I am only left with data from 2021.

The function looks like this:

dataframe_list = [bitcoin, have, binance, Cardano, chainlink, cosmos, crypto com, dogecoin, eos, Ethereum, iota, litecoin, monero, nem, Polkadot, Solana, stellar, tether, uni swap, usdcoin, wrapped, xrp]
def date_func(i):
    i['Date'] = pd.to_datetime(i['Date'])
    i = i.set_index(i['Date'])
    i = i.sort_index()
    i = i['2021-01-01':]
for dataframe in dataframe_list:
    dataframe = date_func(dataframe)

However, I am only left with one data frame called ‘dataframe’, which only contains values of the xrp dataframe.
I would like to have a new dataframe from each dataframe, called aave21, bitcoin21 …. which only contains values from 2021 onwards.

What am I doing wrong?

Best regards and thanks in advance.

Asked By: Max



You are overwriting dataframe when iterating over dataframe_list, i.e. you only keep the latest dataframe.

You can either try:

dataframe = pd.DataFrame()
for df in dataframe_list:

Or shorter:

dataframe = pd.concat([data_func(df) for df in dataframe_list])
Answered By: max_jump

You are overwriting dataframe variable in your for loop when iterating over dataframe_list. You need to keep appending results into a new variable.

final_df = pd.DataFrame()

for dataframe in dataframe_list:
Answered By: Pratik Gujarathi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.