python - 从 Pandas 数据框中删除零

标签 python pandas dataframe indexing

这个问题在其他多个帖子中被问到,但我无法使用任何方法。这是我的数据框:

df = pd.DataFrame([[1,2,3,4.5],[1,2,0,4,5]])

我想知道我该怎么做:

1) 删除包含任何/全零的行 2) 删除包含任何/全零的列

为了删除包含任何零的行,这行得通:

df2 = df[~(df == 0).any(axis=1)]
df2 = df[~(df == 0).all(axis=1)]

但我无法让它按列工作。我试图设置 axis=0 但这给了我这个错误:

__main__:1: UserWarning: Boolean Series key will be reindexed to match DataFrame index.

有什么建议吗?

最佳答案

为此你需要loc:

df
   0  1  2  3  4
0  1  2  3  4  5
1  1  2  0  4  5

df.loc[:, ~(df == 0).any(0)]  # notice the :, this means we are indexing on the columns now, not the rows
   0  1  3  4
0  1  2  4  5
1  1  2  4  5

直接索引默认为行索引。您正在尝试使用 [0, 1, 3, 4] 索引只有两行的数据框,因此 pandas 会警告您。

关于python - 从 Pandas 数据框中删除零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46531994/

相关文章:

python - 如何正确触发 python 扭曲传输?

python - 两个数据帧的 Pandas join.fillna 将所有值替换为,而不仅仅是 nan

python - 使用 Python Pandas 的累积 OLS

python - Pandas ExcelWriter .save() 出错;权限错误 [WinError 32]

r - 过滤到观察第一个特定值

r - 查找数据框中前 n 行的总和

python - 如何检测 Tornado 应用程序中的长阻塞函数

python - 如何自动从工程图图像中裁剪图?

python - 一次随机将 Pandas 数据框分成几组以进行 x 折交叉验证

python - 如何按顺序标记前几个月