python - 过滤掉 MultiIndex 数据框中具有零值的行/列

标签 python pandas

我在 python 中有以下 Pandas MultiIndex 数据框

             0         1         2         3 
bar one  0.000000 -0.929631  0.688818 -1.264180
    two  1.130977  0.063277  0.161366  0.598538
baz one  1.420532  0.052530 -0.701400  0.678847
    two -1.197097  0.314381  0.269551  1.115699
foo one -0.077463  0.437145 -0.202377  0.260864
    two -0.815926 -0.508988 -1.238619  0.899013
qux one -0.347863 -0.999990 -1.428958 -1.488556
    two  1.218567 -0.593987  0.099003  0.800736

我的问题,如何过滤掉:

  1. 包含零值的列 - 在上例中为第 0 列。
  2. 重新升级为行过滤。如何单独过滤带零的行:(bar, one) 以及如何同时过滤 (bar, one) 和 (bar, two)?

    (抱歉我的母语不是英语;)

最佳答案

要过滤掉包含零值的列,您可以使用

df2 = df.loc[:, (df != 0).all(axis=0)]

要过滤掉包含零值的行,您可以使用

df2 = df.loc[(df != 0).all(axis=1), :]

要过滤掉行,您可以使用

df2 = df.drop('bar') ## drops both 'bar one' and 'bar two'
df2 = df.drop(('baz', 'two')) ## drops only 'baz two'

例如,

import numpy as np
arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']), np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]
df = pd.DataFrame(np.random.randn(8, 4), index=arrays)
df.ix['bar','one'][2] = 0
df = df.loc[:, (df != 0).all(axis=0)]
df = df.drop('bar')
df = df.drop(('baz', 'two'))

#                 0         1         3
# baz one  0.686969  0.410614  0.841630
# foo one  1.522938  0.555734 -1.585507
#     two -0.975976  0.522571 -0.041386
# qux one -0.991787  0.154645  0.179536
#     two -0.725685  0.809784  0.394708

如果数据框中没有 NaN 值,另一种方法是将 0 转换为 NaN 并删除具有 NaN 的列或行:

df[df != 0.].dropna(axis=1) # to remove the columns with 0
df[df != 0.].dropna(axis=0) # to remove the rows with 0

最后,如果您想要在有一个零值的情况下删除整个“bar”行,您可以这样做:

indices = df.loc[(df == 0).any(axis=1), :].index.tolist() ## multi-index values that contain 0
for ind in indices:
    df = df.drop(ind[0])

关于python - 过滤掉 MultiIndex 数据框中具有零值的行/列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35996768/

相关文章:

python - 使用 Pandas 将列转换为行

Python Pandas : check if items from list is in df index

python - 根据给定的输入集实现 n 叉树

python - 多线程迭代器

python - tf.estimator 需要 label_data 和 batch_size 进行预测 Tensorflow

python - lxml:如何从树中的给定元素创建新的元素树

python - python/cython 中绝对最快的查找

python - 使用 Pandas 计算加权平均值以降低成本

python - Pandas - 根据列中的列表从数据框中选择行

python - pandas groupby.agg() 采用分类变量的模式,其中 NaN 是组的唯一变量