在MultiIndex数据帧中过滤掉零值的行/列

Dov*_*Dov 2 python pandas

我在python中有以下panda 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
Run Code Online (Sandbox Code Playgroud)

我的问题,如何过滤掉:

  1. 在上面的示例中,包含零值的列 - 列0.
  2. 用rerade到行过滤.我如何单独使用0:(bar,one)过滤行?如何过滤(bar,one)和(bar,two)?

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

Jul*_*nck 7

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

df2 = df.loc[:, (df != 0).all(axis=0)]
Run Code Online (Sandbox Code Playgroud)

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

df2 = df.loc[(df != 0).all(axis=1), :]
Run Code Online (Sandbox Code Playgroud)

要过滤掉行,您可以使用

df2 = df.drop('bar') ## drops both 'bar one' and 'bar two'
df2 = df.drop(('baz', 'two')) ## drops only 'baz two'
Run Code Online (Sandbox Code Playgroud)

例如,

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
Run Code Online (Sandbox Code Playgroud)

如果数据帧中没有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
Run Code Online (Sandbox Code Playgroud)

最后,如果你想删除整个'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])
Run Code Online (Sandbox Code Playgroud)