Search code examples
pythoncsvdataframeconcatenation

Concat dataframes - One with no column name


So I have 2 csv files with the same number of columns. The first csv file has its columns named (age, sex). The second file though doesn't name its columns like the first one but it's data corresponds to the according column of the first csv file. How can I concat them properly?

First csv.
first csv

Second csv.
second csv

This is how I read my files:

df1 = pd.read_csv("input1.csv")
df2 = pd.read_csv("input2.csv", header=None)

I tried using concat() like this but I get 4 columns as a result..

df = pd.concat([df1, df2])

Solution

  • I found a solution. After reading the second file I added

    df2.columns = df1.columns
    

    Works just like I wanted to. I guess I better research more next time :). Thanks

    Final code:

    df1 = pd.read_csv("input1.csv")
    df2 = pd.read_csv("input2.csv", header = None)
    df2.columns = df1.columns
    df = pd.concat([df1, df2])