Merge several columns from multiple csv files to one csv file
Try this:
import pandas as pd
forward = None
for i in range(3):
j = i + 1
t = pd.read_csv(f'E:\\bachelor thesismaterials\\TrainData\\CSV\\Forward_2_4\\F358\\CH{j}.CSV')[f'C{j} in V'].to_frame()
forward = t if forward is None else forward.join(t)
f = 'E:\\bachelor thesis materials\\1d\\Forward_1.csv'
forward.to_csv(f, index=False)
forward = pd.read_csv(f)
print(forward)
Output:
C1 in V C2 in V C3 in V
0 0.008496 0.006152 -0.01221
1 0.010059 0.004199 -0.01709
2 0.012793 0.004004 -0.02275
3 0.014746 0.002246 -0.02803
4 0.018262 0.002441 -0.03311
5 0.020801 0.002441 -0.03936
6 0.019043 0.001855 -0.04443
7 0.018457 -0.000490 -0.04775
How to merge multiple csv files on common columns and keep the non common ones as separate columns?
Idea is create MultiIndex
by DataFrame.set_index
for each DataFrame
, then concat
with axis=1
and last remove index=False
in to_csv
:
cols = ['Province/State', 'Country/Region','Lat','Long','Date']
dfs = [df1, df2, df3]
df_merged = pd.concat([x.set_index(cols) for x in dfs], axis=1)
df_merged.to_csv('merged.csv', sep=',', encoding='utf-8')
Or convert MultiIndex
to column and then use index=False
in to_csv
:
cols = ['Province/State', 'Country/Region','Lat','Long','Date']
dfs = [df1, df2, df3]
df_merged = pd.concat([x.set_index(cols) for x in dfs], axis=1).reset_index()
df_merged.to_csv('merged.csv', sep=',', encoding='utf-8', index=False)
Related Topics
How to Put a Space Between Two String Items in Python
How to Mention a User in Discord.Py
How to Remove All Characters Before a Specific Character in Python
Python Pandas - Get Row Based on Previous Row Value
How to Drop Rows from Pandas Data Frame That Contains a Particular String in a Particular Column
How to Remove Strings Present in a List from a Column in Pandas
How to Clear Only Last One Line in Python Output Console
I Received an Error Message That I Don't Quite Understand
Python: How to Print Separate Lines from a List
How to Update a Pyspark Dataframe With New Values from Another Dataframe
Combine Date and Time Columns Using Python Pandas
Remove Partial String from Dataframe With Pandas
How to Call a Django Function on Button Click
Export Pandas Dataframe into a Pdf File Using Python
Receiving Integers from the User Until They Enter 0
How to Get Interactive Plots Again in Spyder/Ipython/Matplotlib