如果我有以下数据框:
A B C D E
1 1 2 0 1 0
2 0 0 0 1 -1
3 1 1 3 -5 2
4 -3 4 2 6 0
5 2 4 1 9 -1
T 1 2 2 4 1
最后一行是每列的阈值。我想在 python pandas 中计算每列值是否降低其阈值。
期望的输出是;
A B C D E
Count 2 2 3 3 4
但是,我需要用一个通用的解决方案来解决这个问题,而不是针对这些特定的列。因为我有一个大数据集。我无法在代码中为它们中的每一个指定列名。
你能帮我解决这个问题吗?
最佳答案
通过索引选择所有没有 first 的行并通过 DataFrame.lt
进行比较按最后一行,然后 sum
并将 Series
转换为一行 DataFrame
by Series.to_frame
通过 DataFrame.T
进行转置:
df = df.iloc[:-1].lt(df.iloc[-1]).sum().to_frame('count').T
print (df)
A B C D E
count 2 2 3 3 4
使用 DataFrame
构造函数的 Numpy 替代方案:
arr = df.values
df = pd.DataFrame([np.sum(arr[:-1] < arr[-1], axis=0)], columns=df.columns, index=['count'])
print (df)
A B C D E
count 2 2 3 3 4
关于python - Pandas 用特定的阈值计算每一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58428543/