Concatenate Rows of Two Dataframes in Pandas
To horizontally concatenate two dataframes, df_a and df_b, with an equal number of rows without considering keys, use the concat function with the axis parameter set to 1:
<code class="python">pd.concat([df_a, df_b], axis=1)</code>
For example, consider the following two dataframes:
<code class="python">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)</code>
Using the concat function with axis=1, we can concatenate these dataframes column-wise:
<code class="python">pd.concat([df_a, df_b], axis=1)</code>
This will result in a dataframe with the same number of rows (3) and the number of columns equal to the sum of the columns in both dataframes (9):
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
Note that since there are no overlapping columns, the merged dataframe directly combines the columns into a single table.
Additionally, you can merge the dataframes using their indices since they have the same number of rows, which provides the same result:
<code class="python">df_a.merge(df_b, left_index=True, right_index=True)</code>
The above is the detailed content of How to Combine Two DataFrames with Equal Number of Rows in Pandas?. For more information, please follow other related articles on the PHP Chinese website!