【问题标题】:Implementing Excel function countif() in Python on rows在 Python 中对行实现 Excel 函数 countif()
【发布时间】:2019-07-05 12:49:59
【问题描述】:

我有以下 DF1 有 100 列(col_1col_100),我想设置一个条件来只计算列(col_1col_100),其中每个项目的值 > 50专栏Item。在 Excel 中,这相当容易 - 使用函数 COUNTIF()。我们如何在 Python 中实现相同的功能?

Item    col_1   col_2   col_3   col_4   col_5   col_6   col_7   …
item_1  10  5   6   9   4   6   77  …
item_2  3   5   66  76  7   89  33  …

在上表中,结果应该是:

Item    Result
item_1  1
item_2  3

【问题讨论】:

标签: python python-3.x pandas


【解决方案1】:

我会用 DataFrame.transpose() 来做这件事

>>>df
Item    col_1   col_2   col_3   col_4   col_5   col_6   col_7   …
item_1  10  5   6   9   4   6   77  …
item_2  3   5   66  76  7   89  33  …

df1 = df.T
tcol = []

for col in df1.columns:
    tcol.append(len(df1.index[df1[col] > 50].tolist()))

df_total = pd.DataFrame(tcol, columns=['total'])
df = df.join(df_total)

P.S. 可能有一种方法可以逐行进行有条件的求和,但我不知道。如果知道的人能指出如何,将不胜感激!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2021-01-02
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多