Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果存在于另一个数据帧列中,则替换数据帧列中的元素_Python_Pandas_List_Dataframe - Fatal编程技术网

Python 如果存在于另一个数据帧列中,则替换数据帧列中的元素

Python 如果存在于另一个数据帧列中,则替换数据帧列中的元素,python,pandas,list,dataframe,Python,Pandas,List,Dataframe,以下给出了两个数据帧: 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 预期输出:[10,97,32,-1,44,-1,-1],因为34,76和49不在列车中 我尝试的是: for x in test.Alpha:

以下给出了两个数据帧:

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

预期输出:
[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
测试的输出

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

您可以使用
isin

test.loc[~test.Alpha.isin(train.Alpha), 'Alpha'] = -1
测试的输出

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