python - 如何计算 Pandas 多索引的真假?

标签 python python-3.x pandas count multi-index

我在 Pandas 中使用多索引。

示例 1:

'info'       '2002'     '2003'     '2004'
'PID' 'Age'  't1' 't2'  't1' 't2'  't1' 't2'
 101   30     Nan  2     2    1     Nan  Nan
 102   28     2    5     1    Nan   10   100   

我想知道这两个值的东西的数量。

[num] 和 [num] 为真

[Nan] 和 [num] 为真

[Nan] 和 [Nan] 为假

例子2:

'info'       
'PID' 'Age' 'count' 
 101   30      2
 102   28      3

所以我想使用 any(),但我没有解决它。

最佳答案

我认为如果 MultiIndex 也需要在索引中首先检查 notna所有值中的所有值,然后通过 DataFrameGroupBy.any 在列中检查每个第一级 MultiIndex 中的至少一个和最后计数 Truesum:

print (df.index)
MultiIndex(levels=[[101, 102], [28, 30]],
           labels=[[0, 1], [1, 0]])

df = df.notna().groupby(axis=1, level=0).any().sum(axis=1)
#oldier pandas versions
#df = df.notnull().groupby(axis=1, level=0).any().sum(axis=1)

如果索引中没有MultiIndex 添加drop删除 info 级别:

print (df.index)
RangeIndex(start=0, stop=2, step=1)

s = df.drop('info', level=0, axis=1).notnull().groupby(axis=1, level=0).any().sum(axis=1)
print (s)
0    2
1    3
dtype: int64

如果需要按位置创建列,请使用 insert :

df.insert(2, ('info','count'), s)
print (df)
   info             '2002'      '2003'      '2004'       
  'PID' 'Age' count   't1' 't2'   't1' 't2'   't1'   't2'
0   101    30     2    NaN    2      2  1.0    NaN    NaN
1   102    28     3    2.0    5      1  NaN   10.0  100.0

关于python - 如何计算 Pandas 多索引的真假?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51165854/

相关文章:

python - 在单元测试中模拟对象时避免输入类型警告?

python - 初学者 python 循环

python - Pandas read_json : "If using all scalar values, you must pass an index"

python - 检查是否有任何一长串变量不是 None 的优雅方法,并返回不是的那个?

python - flask 不停地限制RESTful API访问

python - 为什么 Flask bool 查询参数总是评估为真?

python - 多处理池 : How to call an arbitrary list of methods on a list of class objects

python - 查找 Pandas 系列中的关键字子集 (Python)

python - 在索引上连接键列

python - 如何使用 Eclipse 和 PyDev 在 Python 中进行相对导入?