python - 获取要删除的行的索引,其中两列为零
问题描述
这是我的专栏:
'CD Block_Code','Total Population Female','Illiterate Female','Total/Rural/Urban'
我想删除女性总人口为零或文盲女性为零的行。
代码
df_cleaned = df.copy(deep = True)
entry_to_remove = [] ;
for index, col in df.iterrows():
if (col['Total Population Female'] == '0') or col['Illiterate Female'] == '0':
entry_to_remove.append(index)
print("entry_to_remove: {}".format(len(entry_to_remove)))
df_cleaned.drop(entry_to_remove, axis = 0, inplace = True)
df_cleaned.head(3)
当我运行最后一个代码时,它给了我零行,实际上只有 634 个是零。
所以会有4个集群,我想分别获取所有4个集群的数据并做进一步分析。
解决方案
一个更简单的方法是使用索引,使用 2 个条件:
df[(df['Illiterate Female']!=0) & (df['Total Population Female']!=0)]
例子:
>>> df
CD Block_Code Illiterate Female Total Population Female
0 0 1 1
1 0 1 1
2 0 1 0
3 0 0 1
>>> df[(df['Illiterate Female']!=0) & (df['Total Population Female']!=0)]
CD Block_Code Illiterate Female Total Population Female
0 0 1 1
1 0 1 1
您还可以根据底层numpy
数组进行过滤,这对于大型数据帧可能更快,但不可否认的是可读性较差:
df[(df[['Illiterate Female','Total Population Female']].values != 0).all(1)]
CD Block_Code Illiterate Female Total Population Female
0 0 1 1
1 0 1 1
推荐阅读
- javafx - JavaFX GridPane 包含未定义的间距
- mfc - 将状态栏添加到 CDialog 并正确设置控件位置
- ios - 将 Firebase 文档计数作为表行计数返回
- python - 将代码同步到异步,无需重写函数
- multithreading - 有一个使用锁的无锁算法有意义吗?
- python - 使用 findall 替换和添加多行
- python - 使用 skimage 调整到更大的分辨率会导致 keras 中的形状类型错误
- c - 在 C 中绘制表格 — 类似于 Linux 手册页上的表格
- ruby - FizzBuzz Ruby 单线
- xaml - Xamarin.Forms 字符串格式不显示绑定信息