Skip to content
Advertisement

Trying to merge different files csv and to label the columns

I’m trying to get a single dataset by merging several cvs files within one folder. So I would like to merge the different file, which each have 4 columns. I would also like to label the four columns using names=[] in pd.concatenate. I’m using this code:

path = r'C:UserschiarDesktopfolder' # defining the path
all_files = glob.glob(path + "/*.csv")
df = pd.concat((pd.read_csv(f) for f in all_files), ignore_index=True, names=['quat_1', 'quat_2', 'quat_3', 'quat_4'])

The problem is that instead of getting 4 columns I get 25, and I don’t get labeling. Could someone tell me what I’m doing wrong? Thank you very much!

Advertisement

Answer

Use parameter names in read_csv if no header in files:

name = ['quat_1', 'quat_2', 'quat_3', 'quat_4']
df = pd.concat((pd.read_csv(f, names=names) for f in all_files), ignore_index=True)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement