python - 在 Pandas 中,当使用 "where"选择时,删除不满足条件的列,而不是用 NaN 填充

标签 python pandas

在 Numpy 中,使用 where 将为您提供原始数组的子集。例如,

import numpy as np
np.where(np.arange(5)>2)[0]

将返回array([3, 4])。我想对 Pandas 做类似的事情。但是,如果我像这样定义一个类似的 DataFrame:

import pandas as pd
df = pd.DataFrame(data=range(5)).T

生成一个 df ,看起来像

   0  1  2  3  4
0  0  1  2  3  4

并申请

df.where(lambda x: x>2)

我明白了

    0   1   2  3  4
0 NaN NaN NaN  3  4

但是,我想得到这个:

    3  4
0   3  4

省略不满足条件的列。如何做到这一点?

最佳答案

IIUC 您可以调用 dropna 传递 axis=1 来删除包含任何 NaN 值的列:

In [272]:
df[df > 2].dropna(axis=1)

Out[272]:
   3  4
0  3  4

关于python - 在 Pandas 中,当使用 "where"选择时,删除不满足条件的列,而不是用 NaN 填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38656930/

相关文章:

python - 超过 url Tensorflow Serving Python 请求的最大重试次数

python - 如何根据属性值将数组拆分为另一个数组?

python - Pandas 数据帧 : How to split one column into multiple one-hot-encoded columns

python - 仅在点图中的 x 轴上显示整数

python - Azure 计费 API 问题

python - scikit-learn : ValueError: not enough values to unpack (expected 2, 得到 1)

python - 使用 pandas.merge() 时为所有列名添加后缀

python - 如何将数据帧行乘以基于行的 'attribute' 的数组?

python - 前向填充 pandas 列不是使用最后一个值,而是使用非空和空元素的平均值

python - sudo pip3 install pygame 和 sudo apt install python3-pygame 有什么区别