Given that I'm reading N csv files and merging them into a single Pandas DataFrame like:
dfs = [pd.read_csv(f) for f in list_of_files]
df = pd.concat(dfs, axis=1)
How can I rename the columns from each file, so that they include a suffix based on the file name?
For example, if files f1 and f2 have the following contents:
f1:
A
1
2
3
f2:
B
4
5
6
Then the column-wise concat
above produces:
A B
1 4
2 5
3 6
... but I want:
A_f1 B_f2
1 4
2 5
3 6
Change your dfs to dict
dfs = {'f'+str(i+1) : pd.read_csv(f) for i,f in enumerate(list_of_files)}
Then using cancat
s=pd.concat(dfs,1)
s.columns=s.columns.map('{0[1]}_{0[0]}'.format)
s
Out[311]:
A_f1 B_f2
0 1 4
1 2 5
2 3 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With