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

标签 python pandas

大家好,我有一个简单的问题,我试图在数据帧(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()

关于Python:在 Pandas 数据框中获取位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43918074/

相关文章:

python - 如何在不使用 cv2.getRotationMatrix2D 的情况下手动旋转图像

python - 嵌套列表或集合理解的正确语法

python - Pandas 多级索引弄乱了类型?

python - Pandas :搜索并将值添加到多列的单元格

Python3 - 为什么这段代码出现在索引之外?

python - 使用切片的 numpy 数组赋值

python - 基于正则表达式解析路径 - Python

python - pandas - 选择关于属性的最后 n 行数据框

python - 如何使用 itertools 提取 groupby 值?

python - 如何更改满足 Pandas 特定条件的行的值?