这个问题在其他多个帖子中被问到,但我无法使用任何方法。这是我的数据框:
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/