Home > database >  Horizontal concatenating dataframes without taking into account the index
Horizontal concatenating dataframes without taking into account the index

Time:11-29

I'm stucked with womething chich looks super easy:

I have a dafatframe df1

df1 = pd.DataFrame(np.random.randint(25, size=(4, 4)),
                   index=["1", "2", "3", "4"],
                   columns=["A", "B", "C", "D"])

enter image description here

I have another dafatframe df2:

df2 = pd.DataFrame(np.random.randint(25, size=(4, 2)),
                   index=["5", "6", "7", "8"],
                   columns=["A", "F"])

enter image description here

They dont have the same index but I want to concatenate them so that I have something like this:

df_final = pd.DataFrame(np.random.randint(25, size=(4, 6)),
                   index=["1", "2", "3", "4"],
                   columns=["A", "B", "C", "D","A","F"])

enter image description here

I don't care about the index, it may be df1's index or something else.

I tried different codes but such as

horizontal_concat_init_index = pd.concat([df1, df2], axis=1).reindex(df1.index)

or

horizontal_concat_ignore_index = pd.concat([df1, df2], ignore_index=True, axis=0)

I don't know what to do, I'm lost, can you help me?

CodePudding user response:

Unfortunately ignore_index only works on the axis you are trying to concat (which should be axis 1). You could remove the index before the concat:

pd.concat([df1.reset_index(drop=True), df2.reset_index(drop=True)], axis=1)
  • Related