Skip to main content
 首页 » 编程设计

python之如何使用 .loc 对 DF 进行切片,列表中可能包含在索引/列中找不到的元素

2025年05月04日20cyq1162

我有几个列表,其中可能包含在 DataFrame 的索引/列中找不到的元素。我想使用这些索引获取特定的行/列,这样如果在索引/列中找不到列表中的元素,那么它就会被忽略。

df1 = pd.DataFrame({"x":[1, 2, 3, 4, 5],  
   "y":[3, 4, 5, 6, 7]},  
   index=['a', 'b', 'c', 'd', 'e']) 
 
df1.loc[['c', 'd', 'e', 'f'], ['x', 'z']] 

我想得到:

     x  
c  3.0 
d  4.0 
e  5.0 

代替:

     x   z 
c  3.0 NaN 
d  4.0 NaN 
e  5.0 NaN 
f  NaN NaN 

请您参考如下方法:

我想你需要Index.intersection :

a = ['c', 'd', 'e', 'f'] 
b =  ['x', 'z'] 
 
print (df1.index.intersection(a)) 
Index(['c', 'd', 'e'], dtype='object') 
 
print (df1.columns.intersection(b)) 
Index(['x'], dtype='object') 
 
df2 = df1.loc[df1.index.intersection(a),df1.columns.intersection(b)] 
print (df2) 
   x 
c  3 
d  4 
e  5