首頁  >  文章  >  後端開發  >  如何在 Pandas 中合併兩個行數相等的 DataFrame?

如何在 Pandas 中合併兩個行數相等的 DataFrame?

Barbara Streisand
Barbara Streisand原創
2024-10-26 19:40:03327瀏覽

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

連接Pandas 中兩個資料幀的行

水平連接兩個資料幀df_a 和df_b,行數相等,而不考慮鍵,使用concat 函數並將axis 參數設為1:

<code class="python">pd.concat([df_a, df_b], axis=1)</code>

例如,考慮以下兩個資料幀:

<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>

使用axis=1 的concat 函數,我們可以按列連接這些資料幀:

<code class="python">pd.concat([df_a, df_b], axis=1)</code>

這將產生一個具有相同行數(3) 且列數等於兩個資料幀中列數總和(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  

請注意,由於沒有重疊的列,合併後的資料框直接將列組合成一個表。

此外,您可以使用它們的索引來合併資料框,因為它們有相同的行數,提供相同的結果:

<code class="python">df_a.merge(df_b, left_index=True, right_index=True)</code>

以上是如何在 Pandas 中合併兩個行數相等的 DataFrame?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn