给定以下列表:
a = ['1', '2', '12', '5']
我正在尝试从 Dataframes 单元格中删除与列表中的元素不匹配的所有值。我确信列表中的每个值在 Dataframe 的每一行中只出现一次。
test = pd.DataFrame({'0' : ['1','4','5','5'],
'1' : ['4','1','12','10'],
'2' : ['10','12','4','2'],
'3' : ['2','10','10','4'],
'4' : ['5','2','2','1'],
'5' : ['12','5','1','12']})
0 1 2 3 4 5
0 1 4 10 2 5 12
1 4 1 12 10 2 5
2 5 12 4 10 2 1
3 5 10 2 4 1 12
重要的方面是维护 Dataframe 中列表中匹配数字的顺序。
结果应该是这样的:
0 1 2 3
0 1 2 5 12
1 1 12 2 5
2 5 12 2 1
3 5 2 1 12
提前致谢!
请您参考如下方法:
使用Series.isin
与 DataFrame.apply
:
#pandas 0.24+
df = test.apply(lambda x: pd.Series(x[x.isin(a)].to_numpy()), axis=1)
#pandas below
df = test.apply(lambda x: pd.Series(x[x.isin(a)].values), axis=1)
print (df)
0 1 2 3
0 1 2 5 12
1 1 12 2 5
2 5 12 2 1
3 5 2 1 12