Python 3.x 计算列中的项目(Python)

Python 3.x 计算列中的项目(Python),python-3.x,pandas,count,Python 3.x,Pandas,Count,使用熊猫中的CSV文件,如何计算一列中有多少项超过指定值?演示: In [21]: df = pd.DataFrame(np.random.randint(100, size=(20, 3)), columns=list('abc')) In [22]: df Out[22]: a b c 0 63 37 33 1 47 40 85 2 82 52 7 3 80 10 90 4 69 21 47 5 89 56 98 6

使用熊猫中的CSV文件,如何计算一列中有多少项超过指定值?

演示:

In [21]: df = pd.DataFrame(np.random.randint(100, size=(20, 3)), columns=list('abc'))

In [22]: df
Out[22]:
     a   b   c
0   63  37  33
1   47  40  85
2   82  52   7
3   80  10  90
4   69  21  47
5   89  56  98
6   25  93  84
7   56  95  71
8   94  61  49
9   42  66  97
10  27  47  66
11  69  78  50
12  68   4  38
13  60  89  10
14  17  27  19
15  66  68  47
16  95  75  23
17  99  68  98
18  79  98  33
19  27  78  86

In [23]: df[['a','c']].gt(50).sum()
Out[23]:
a    14
c     9
dtype: int64

In [24]: df[['a','c']].gt(50)
Out[24]:
        a      c
0    True  False
1   False   True
2    True  False
3    True   True
4    True  False
5    True   True
6   False   True
7    True   True
8    True  False
9   False   True
10  False   True
11   True  False
12   True  False
13   True  False
14  False  False
15   True  False
16   True  False
17   True   True
18   True  False
19  False   True
演示:


假设您有一个数据帧
df
,其数字列名为
value
。以下是计算大于3的
value
元素数的一些方法:

df[df.value > 3].shape[0]
len(df[df.value > 3])
df[df.value > 3].count()

请注意,
shape
len
将计算NaN值,而
count
将从计数中排除NaN。

假设您有一个名为
value
的数据框
df
。以下是计算大于3的
value
元素数的一些方法:

df[df.value > 3].shape[0]
len(df[df.value > 3])
df[df.value > 3].count()

请注意,
shape
len
将计算NaN值,而
count
将从计数中排除NaN。

此问题包含两部分:

  • 将CSV读入数据框:

    import pandas as pd
    df = pd.read_csv('/where/ever/your/file/is/located')
    
  • 假设您已经有了数据帧,那么您可以执行以下操作:

    # selecting the rows on 'a' > 100
    df2 = df[df['a'] > 100 ]
    print(len(df2))
    

  • 这个问题包括两部分:

  • 将CSV读入数据框:

    import pandas as pd
    df = pd.read_csv('/where/ever/your/file/is/located')
    
  • 假设您已经有了数据帧,那么您可以执行以下操作:

    # selecting the rows on 'a' > 100
    df2 = df[df['a'] > 100 ]
    print(len(df2))