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()函数查找“单位”列值的计数-
print"Count of values of Units column from DataFrame1 = ",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