如何在不考慮鍵或列差異的情況下水平連接 Pandas DataFrame?

Linda Hamilton
發布: 2024-10-27 21:04:30
原創
112 人瀏覽過

How can I horizontally concatenate Pandas DataFrames without considering keys or column differences?

在Pandas 中水平連接DataFrame

要水平連接兩個DataFrame,而不考慮鍵和列數的潛在差異,請使用concat具有axis=1 參數的函數。此參數指定應按列執行串聯。

範例:

考慮以下兩個DataFrame,df_a 和df_b,行數相同但不同列數:

<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)</code>
登入後複製

要水平連接這些DataFrame,請使用以下程式碼:

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

這將建立一個新的DataFrame,其行數與原始DataFrame 相同,且列數等於兩個DataFrame 中列的總和。產生的 DataFrame 將如下所示:

       AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  Treatment1  inte1
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1          C   1100
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1          C   1050
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1          C   1010
登入後複製

替代方法:

根據特定要求,還有替代方法來水平連接 DataFrame。

  • 與索引合併:如果 DataFrame 具有相同的行數且沒有衝突的列名稱,則可以使用 left_index=True 和 right_index=True 的合併功能。這將根據索引合併 DataFrame。
  • Join: 與合併方法類似,join 函數也可用於水平連接 DataFrame。當您想要連接具有不同索引的 DataFrame 時,它特別有用。

以上是如何在不考慮鍵或列差異的情況下水平連接 Pandas DataFrame?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!