Pandas GroupBy – 计算每个组合的出现次数
为了对列进行分组并计算Pandas中每个组合的出现次数,我们使用with。该方法将DataFrame分成多个组。DataFrame.groupby()size()groupby()
首先,让我们使用别名pd导入pandas库-
import pandas as pd
初始化列表数据-
# initializing the data mylist = {'Car': ['BMW', 'Mercedes', 'Lamborgini', 'Audi', 'Mercedes', 'Porche', 'RollsRoyce', 'BMW'], 'Place': ['Delhi', 'Hyderabad', 'Chandigarh', 'Bangalore', 'Hyderabad', 'Mumbai', 'Mumbai','Delhi'], 'Sold': [95, 80, 80, 75, 90, 90, 95, 50 ]}
接下来,我们将创建一个DataFrame-
# DataFrame dataFrame = pd.DataFrame(mylist, columns=['Car', 'Place', 'Sold'])
现在,使用groupby()来计算出现的次数size()-
print("计算发生的次数...") res = dataFrame.groupby(['Car', 'Place']).size()
以下是计算每个组合出现次数的代码-
示例
# importing library import pandas as pd # initializing the data mylist = {'Car': ['BMW', 'Mercedes', 'Lamborgini', 'Audi', 'Mercedes', 'Porsche', 'RollsRoyce', 'BMW'], 'Place': ['Delhi', 'Hyderabad', 'Chandigarh', 'Bangalore', 'Hyderabad', 'Mumbai', 'Mumbai','Delhi'], 'Sold': [95, 80, 80, 75, 90, 90, 95, 50 ]} # DataFrame dataFrame = pd.DataFrame(mylist, columns=['Car', 'Place', 'Sold']) print(dataFrame) print("计算发生的次数...") res = dataFrame.groupby(['Car', 'Place']).size() # Displaying the occurrences print(res)输出结果
这将产生以下输出-
Car Place Sold 0 BMW Delhi 95 1 Mercedes Hyderabad 80 2 Lamborgini Chandigarh 80 3 Audi Bangalore 75 4 Mercedes Hyderabad 90 5 Porsche Mumbai 90 6 RollsRoyce Mumbai 95 7 BMW Delhi 50 计算发生的次数... Car Place Audi Bangalore 1 BMW Delhi 2 Lamborgini Chandigarh 1 Mercedes Hyderabad 2 Porsche Mumbai 1 RollsRoyce Mumbai 1 dtype: int64