【问题标题】:Delete zeros from a pandas dataframe从熊猫数据框中删除零
【发布时间】:2017-10-02 19:01:20
【问题描述】:

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

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.

有什么建议吗?

【问题讨论】:

    标签: python pandas dataframe indexing


    【解决方案1】:

    你需要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 会警告您。

    【讨论】:

    • 鉴于数据的顺序性,我相信它应该以4, 5 结尾,而不是4.5。另外,我认为您的 any 方法中不需要零,即 any() 应该可以工作。
    • @Alexander heheh,永远不会意识到。谢谢。
    • @Alexander:很好的收获。实际上这就是它最初发生的方式,但从那以后我一直保持这种状态以创建一个缺失值,因此我可以不时测试 dropna(),我倾向于忘记轴是如何在 dropna() 中定义的。
    • @NiccolaTartaglia 也许最好将np.NaN明确添加为第一行的最后一个元素。
    • @Alexander:哦,是的,这是一个更好的选择。感谢您指出这一点!!!
    猜你喜欢
    • 2014-05-04
    • 1970-01-01
    • 2016-04-30
    • 2020-03-23
    • 1970-01-01
    • 2020-05-28
    • 2018-03-15
    • 2016-08-09
    • 1970-01-01
    相关资源
    最近更新 更多