Reputation: 526
how to join dataframes without losing their names
I have several dataframes in a list and by joining them I am losing the identification of each one because they have equal columns.
ticker_list = ['SBSP3.SA', 'CSMG3.SA', 'CGAS5.SA']
pd_list = [pd.read_csv('{}.csv'.format(ticker)) for ticker in ticker_list]
for index, df in enumerate(pd_list):
df['source'] = ticker_list[index]
df = pd.concat(pd_list,axis = 1)
I'm getting the following output:
as the dataframes have columns equal I just don't know which entry belongs to which csv file
how do i put the identification of each one in the dungeons? example:
Date High_SBSP3.SA Low_SBSP3.SA Open_SBSP3.SA Close_SBSP3.SA Volume_SBSP3.SA Adj Close_SBSP3.SA
0 2017-01-02 14.70 14.60 14.64 14.66 7525700.0 13.880955
1 2017-01-03 15.65 14.95 14.95 15.50 39947800.0 14.676315
2 2017-01-04 15.68 15.31 15.45 15.50 37071700.0 14.676315
3 2017-01-05 15.91 15.62 15.70 15.75 47586300.0 14.913031
4 2017-01-06 15.92 15.50 15.78 15.66 25592000.0 14.827814
Upvotes: 1
Views: 51
Reputation: 59274
Use add_sufix
when reading.
pd_list = [pd.read_csv(f'{ticker}.csv').add_suffix(ticker) for ticker in ticker_list]
OR you can concat
through axis=0
and define the ticker as another columns
pd_list = [pd.read_csv(f'{ticker}.csv').assign(ticker=ticker) for ticker in ticker_list]
df = pd.concat(pd_list)
Upvotes: 1