Home > Article > Backend Development > How can I combine two Pandas DataFrames horizontally (column-wise) in Python, similar to the `cbind` function in R?
Question:
How can I combine two dataframes horizontally (column-wise) in Python's Pandas library, similar to the cbind function in R?
Solution:
To concatenate dataframes horizontally without considering keys, use the pd.concat() function with the axis=1 parameter. This parameter specifies concatenation along the columns:
<code class="python">result = pd.concat([df_a, df_b], axis=1)</code>
Example:
Consider the following example:
<code class="python">import pandas as pd dict_data = {'Treatment': ['C', 'C', 'C'], 'Biorep': ['A', 'A', 'A'], 'Techrep': [1, 1, 1], 'AAseq': ['ELVISLIVES', 'ELVISLIVES', 'ELVISLIVES'], 'mz':[500.0, 500.5, 501.0]} df_a = pd.DataFrame(dict_data) dict_data = {'Treatment1': ['C', 'C', 'C'], 'Biorep1': ['A', 'A', 'A'], 'Techrep1': [1, 1, 1], 'AAseq1': ['ELVISLIVES', 'ELVISLIVES', 'ELVISLIVES'], 'inte1':[1100.0, 1050.0, 1010.0]} df_b = pd.DataFrame(dict_data) result = pd.concat([df_a, df_b], axis=1) print(result)</code>
Output:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \ 0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1 1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1 2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1 Treatment1 inte1 0 C 1100 1 C 1050 2 C 1010
As you can see, the resulting dataframe has the same number of rows and columns as the sum of the two original dataframes.
Alternative Methods:
In addition to pd.concat(), you can also use merge() or join() for blind columnar concatenation. However, these methods require matching indices or keys between the dataframes:
<code class="python"># Using merge() result = df_a.merge(df_b, left_index=True, right_index=True) # Using join() result = df_a.join(df_b)</code>
The above is the detailed content of How can I combine two Pandas DataFrames horizontally (column-wise) in Python, similar to the `cbind` function in R?. For more information, please follow other related articles on the PHP Chinese website!