簡體   English   中英

如何連接DataFrames而不重復列並保持默認左邊或不是NaN,使用python pandas?

[英]How to join DataFrames without duplicating columns and keep default left of right or not NaN, with python pandas?

我想在索引上合並兩個DataFrame(因此join() )。
但是這兩個DataFrame有大約20列,完全相同。 我希望避免重復列作為決定保留哪些,刪除其中一半並重命名其他列可能很麻煩。

我的目標是將一個DataFrame(我稱之為“舊”)作為所有以前DataFrames的歷史記錄。 所以我正在構建一個新的數據幀,然后將它合並到它的舊自我等等。舊的DataFrame將隨着迭代次數的增加而增加。

這是一個簡化的例子

import pandas as pd
df = pd.DataFrame({'A': [1,2,3],
              'B': [4,5,6],
              'C':[7,8,9]}
     ).set_index([[11,22,33]])

old = df.head(2)
new = df.tail(2)

print( old.join(new,how='outer', lsuffix='_left') )

這使 :

    A_left  B_left  C_left    A    B    C
11     1.0     4.0     7.0  NaN  NaN  NaN
22     2.0     5.0     8.0  2.0  5.0  8.0
33     NaN     NaN     NaN  3.0  6.0  9.0
  • 11 :我知道如果新ID中不存在ID,則應該保留它,而不是使用NaN創建重復變量。

  • 22 :如果兩者都存在ID,則應覆蓋舊值; 丟棄_left列,保持_right的。

  • 33 :如果舊的ID不存在,則新增,只需追加即可

我為此搜索了很多文檔,但找不到任何東西。

到目前為止,我最好的想法是使用后綴進行連接,然后應用過濾器:如果cols A_left,B_left C_left是NaN,則復制A,B,C中的值。 刪除cols A_left,B_left C_left等。
這似乎不是一個好的有效解決方案。

或者可能追加它們,sort_values然后刪除重復的id?

由於我是Python新手,這可能不是最好的方法,請告訴我。

------------------評論后編輯----------------------------- -

第一個選項,完整代碼:它保留兩者的索引,同時更新具有相同索引但具有不同值的行與來自new的值。

import pandas as pd
old = pd.DataFrame({'A': [2,3,4],
              'B': [5,6,4],
              'C':[8,9,4]}
     ).set_index([[22,33,44]])

new = pd.DataFrame({'A': [1,2,3],
              'B': [44,55,66],
              'C':[7,8,9]}
     ).set_index([[11,22,33]])

new
    A   B   C
11  1   44  7
22  2   55  8
33  3   66  9

old
    A   B   C
22  2   5   8
33  3   6   9
44  4   4   4

pd.merge(new, old, on=['A','B','C'], how='outer', right_index=True, left_index=True)

output:
    A   B   C
11  1   44  7
22  2   55  8
33  3   66  9
44  4   4   4

你試過合並嗎?

    pd.merge(old, new, on=['A','B','C'], how='outer', left_index=True, right_index=True))

Output:

        A   B   C
    11  1   4   7
    22  2   5   8
    33  3   6   9

選項2:使用追加和刪除重復項:

new.append(old).drop_duplicates()

你可以試試這個,我想它會對你有用!

import pandas as pd

df = pd.DataFrame({'A': [1,2,3,4],
              'B': [4,5,6,7],
              'C':[7,8,9,10],
              'D':[10,11,12,14]}
     ).set_index([[11,22,33,44]])

df2 = pd.DataFrame({'A': [1,2,3,4],
              'B': [4,5,6,8],
              'C':[11,12,13,15],
              'D':[14,15,16,17]}
     ).set_index([[11,22,33,44]])
old = df.head(3)
new = df2.tail(3)

intersection = list(set(list(new.index)).intersection(list(old.index)))
old.loc[intersection] = new.loc[intersection]
only_new = [x for x in list(new.index) if x not in list(old.index)]

old.loc[only_new] = new.loc[only_new]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM