gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:40:21 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com