1
$\begingroup$

I have 2 Dataframes as shown and I want a new DataFrame where the 1st column is the 1st column of the 1st DataFrame and 2nd column from the 1st column of the 2nd DataFrame. I have tried pivot table etc but have no luck.

    A   B
0   1   2
1   3   67
2   4   54
    C   D
0   0   19
1   23  6
2   55  5

I need a new DataFrame like this.

    A   C   B   D
0   1   0   2   19
1   3   23  67  6
2   4   55  54  5
$\endgroup$

2 Answers 2

3
$\begingroup$

Use pandas.DataFrame.reindex()

df = pd.concat((df1, df2), axis=1)

#reorder columns
column_names=["A","C","B","D"]
df = df.reindex(columns=column_names)

$\endgroup$
1
  • 1
    $\begingroup$ why is this so flaming unintuitive? I've been working in python for 5+ years and literally have to look this up weekly beause pandas can't keep consistent syntax with similar functions and operate like df.concat(df2, axis=1)??? $\endgroup$
    – Garglesoap
    Mar 30, 2022 at 15:19
0
$\begingroup$

I'd do pandas.concat and then reorder my columns. Something like this:

# Concatenate along axis 1
df_new = pd.concat((df1, df2), axis=1)

# New order of columns, interleaved in this case
new_cols_order = np.array(list(zip(df1.columns, df2.columns))).flatten()

# Reorder columns
df_new = df_new[new_cols_order]

Edit: I noticed the answer from Dee, which came after mine despite not involving any novelty at all. Also, my solution let's you achieve your goal without specifying the column order manually.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.