Python - 计算 Pandas DataFrame 列值的数量


要计算列值的数量,请使用 count() 方法。首先,导入所需的 Pandas 库 −

import pandas as pd

使用两列创建 DataFrame −

dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'], "Units": [100, 150, 110, 80, 110, 90] } )

使用 count() 函数查找“Units”列值的数量 −

print"Count of values of Units column from DataFrame1 = ",dataFrame1['Units'].count()

通过同样的方式,我们计算了第 2 个 DataFrame 的数量。

示例

以下是完整代码 −

Open Compiler
import pandas as pd # Create DataFrame1 dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'], "Units": [100, 150, 110, 80, 110, 90] } ) print"DataFrame1 ...\n",dataFrame1 # Finding count of values of a specific column print"Count of values of Units column from DataFrame1 = ",dataFrame1['Units'].count() # Create DataFrame2 dataFrame2 = pd.DataFrame( { "Product": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD'], "Price": [8000, 500, 3000, 1500, 3000] } ) print"\nDataFrame2 ...\n",dataFrame2 # Finding count of values of all the column print"\nCount of column values from DataFrame2 = \n",dataFrame2.count()

输出

这将产生以下输出 −

DataFrame1 ...
       Car   Units
0      BMW    100
1    Lexus    150
2     Audi    110
3    Tesla     80
4  Bentley    110
5   Jaguar     90
Count of values of Units column from DataFrame1 = 6

DataFrame2 ...
    Price   Product
0   8000    TV
1    500    PenDrive
2   3000    HeadPhone
3   1500    EarPhone
4   3000    HDD

Count of column values from DataFrame2 =
Price     5
Product   5
dtype: int64

更新于: 2021-09-15

969 次浏览

开启你的 职业生涯

完成课程,获得认证

立即开始
广告