簡體   English   中英

替換 pandas dataframe 列中的元素(如果存在於另一個 dataframe 列中)

[英]Replace an element in a pandas dataframe column if present in another dataframe column

有兩個數據框由:

train = pd.DataFrame({'Alpha': [10, 22, 10, 45, 44, 21, 62, 84, 32, 97, 38]})
test = pd.DataFrame({'Alpha': [10, 97, 32, 34, 44, 76, 49]})

如果訓練中存在每個測試值,則應將測試值替換為 -1。

預期的 output: [10, 97, 32, -1, 44, -1, -1]因為 34、76 和 49 不存在於火車中。

我嘗試了什么:

for x in test.Alpha:
    if x not in train.Alpha:
        test = test.Alpha.replace(x, -1)

不工作。

您可以使用isin

test.loc[~test.Alpha.isin(train.Alpha), 'Alpha'] = -1

Output test

   Alpha
0     10
1     97
2     32
3     -1
4     44
5     -1
6     -1

暫無
暫無

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

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