簡體   English   中英

在條件 Pandas 上加入 DataFrames

[英]Join DataFrames on Condition Pandas

我有以下兩個要合並的具有二進制值的數據框。

df1

    Action  Adventure   Animation   Biography   
0   0       1           0           0   
1   0       0           0           0   
2   1       0           0           0   
3   0       0           0           0   
4   1       0           0           0

df2

    Action  Adventure   Biography   Comedy  
0   0       0           0           0   
1   0       0           1           0   
2   0       0           0           0   
3   0       0           0           1   
4   1       0           0           0   

我想以結果具有不同列的方式連接這兩個數據幀,如果在一個數據幀中值為 1,則結果為 1,否則為 0。

結果

    Action  Adventure   Animation   Biography   Comedy
0   0       1           0           0           0
1   0       0           0           1           0
2   1       0           0           0           0
3   0       0           0           0           1 
4   1       0           0           0           0

我堅持這一點,所以我沒有建議的解決方案。

讓我們add兩個數據框,然后clip上限值:

df1.add(df2, fill_value=0).clip(upper=1).astype(int)

   Action  Adventure  Animation  Biography  Comedy
0       0          1          0          0       0
1       0          0          0          1       0
2       1          0          0          0       0
3       0          0          0          0       1
4       1          0          0          0       0

將其視為設定問題可能會給您解決方案。 看看代碼。

print((df1 | df2).fillna(0).astype(int) | df2)

完整代碼:

import pandas as pd

df1 = pd.DataFrame(
    {
        'Action':[0, 0, 1, 0, 1],
        'Adventure':[1, 0, 0, 0, 0],
        'Animation':[0, 0, 0, 0, 0],
        'Biography':[0, 0, 0, 0, 0]
    }
)

df2 = pd.DataFrame(
    {
        'Action':[0, 0, 1, 0, 1],
        'Adventure':[1, 0, 0, 0, 0],
        'Animation':[0, 0, 0, 0, 0],
        'Biography':[0, 1, 0, 0, 0],
        'Comedy':[0, 0, 0, 1, 0]
    }
)

print((df1 | df2).fillna(0).astype(int) | df2)

輸出:

   Action  Adventure  Animation  Biography  Comedy
0       0          1          0          0       0
1       0          0          0          1       0
2       1          0          0          0       0
3       0          0          0          0       1
4       1          0          0          0       0

暫無
暫無

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

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