首頁  >  文章  >  後端開發  >  如何在 Python 中水平(按列)組合兩個 Pandas DataFrame,類似於 R 中的“cbind”函數?

如何在 Python 中水平(按列)組合兩個 Pandas DataFrame,類似於 R 中的“cbind”函數?

Barbara Streisand
Barbara Streisand原創
2024-10-27 08:35:03564瀏覽

How can I combine two Pandas DataFrames horizontally (column-wise) in Python, similar to the `cbind` function in R?

連接Pandas 中兩個資料幀的行

問題:
如何在Python 中水平(按列)組合兩個資料幀Pandas 函式庫,類似R 中的cbind 函數?

解決方案:
要水平連接資料幀而不考慮鍵,請使用帶有 axis=1 參數的 pd.concat() 函數。此參數指定沿列的串聯:

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

示例:
考慮以下示例:

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

輸出:

        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  

如您所見,產生的資料幀的行數和列數與兩個原始資料幀的總和相同。

替代方法:
除了 pd.concat() 之外,還可以使用 merge() 或 join() 進行盲列連接。但是,這些方法需要資料幀之間匹配索引或鍵:

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

以上是如何在 Python 中水平(按列)組合兩個 Pandas DataFrame,類似於 R 中的“cbind”函數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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