Python - 计算 Pandas DataFrame 的列值数量

pythonserver side programmingprogramming更新于 2025/10/29 6:04:17

要计算列值数量,请使用 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"DataFrame1 中 Units 列的值计数 = ",dataFrame1['Units'].count()

以同样的方式,我们计算了第二个 DataFrame 的计数。

示例

以下是完整代码 −


import pandas as pd

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

print"DataFrame1 ...\n",dataFrame1

# 查找特定列的值的数量
print"Count of values of Units column from DataFrame1 = ",dataFrame1['Units'].count()

# 创建 DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Product": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD'],
      "Price": [8000, 500, 3000, 1500, 3000]
   }
)

print"\nDataFrame2 ...\n",dataFrame2

# 查找所有列的值的数量
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

相关文章


有用资源