How to Combine Two DataFrames with Equal Number of Rows in Pandas?

Barbara Streisand
Release: 2024-10-26 19:40:03
Original
332 people have browsed it

How to Combine Two DataFrames with Equal Number of Rows in Pandas?

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>
Copy after login
Copy after login

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>
Copy after login

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>
Copy after login
Copy after login

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  
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!