Skip to main content
 首页 » 编程设计

Python:在 Pandas 数据框中获取位置

2025年05月04日25kenshinobiy

大家好,我有一个简单的问题,我试图在数据帧(B 列)中找到所有 NaN 字段的 iloc 行位置。到目前为止,我正在通过以下方式解决问题:

rng= ['AA', 'BB', 2, 3, 4, 5] 
df1 = pd.DataFrame(np.random.randn(6, 3), index=rng, columns=['A', 'B', 'C']) 
df1.iloc[1][1]= np.nan 
 
+----------------------------------+ 
|            A         B         C | 
+----------------------------------+ 
| AA  0.198267 -1.469309 -1.751756 | 
| BB -1.376388       Nan  0.988391 | 
| 2  -1.697636 -0.814975  0.614170 | 
| 3  -1.187977  1.240791 -1.079049 | 
| 4  -1.495139  0.215619 -1.572205 | 
| 5   1.157736 -0.656647 -0.307207 | 
+----------------------------------+ 
 
ind_com=df1.loc[df1.B.isnull()].index.values.tolist() 
ind_list=[] 
for ii in ind_com: 
    ind_list.append(df_temp.index.get_loc(ii)) 

ind_list = 1 当然必须有更好的方法。 谢谢

请您参考如下方法:

我认为你需要:

pos = [df1.index.get_loc(x) for x in df1.index[df1.B.isnull()]] 

另一种解决方案 numpy.where :

pos = np.where(df1.B.isnull().values)[0].tolist() 

或numpy.nonzero :

pos = np.nonzero(df1.B.isnull().values)[0].tolist()