[英]After binning a column of a dataframe, how to make a new dataframe to count the number of elements in each bin?
說我有一個數據框df
:
>>> df
Age Score
19 1
20 2
24 3
19 2
24 3
24 1
24 3
20 1
19 1
20 3
22 2
22 1
我想構造一個新的數據框來對Age
並在不同的Score
列中存儲每個分類中的元素總數:
Age Score 1 Score 2 Score 3
19-21 2 4 3
22-24 2 2 9
這是我的操作方式,我感到非常費解(意思是,這不應該那么困難):
import numpy as np
import pandas as pd
data = pd.DataFrame(columns=['Age', 'Score'])
data['Age'] = [19,20,24,19,24,24,24,20,19,20,22,22]
data['Score'] = [1,2,3,2,3,1,3,1,1,3,2,1]
_, bins = np.histogram(data['Age'], 2)
labels = ['{}-{}'.format(i + 1, j) for i, j in zip(bins[:-1], bins[1:])] #dynamically create labels
labels[0] = '{}-{}'.format(bins[0], bins[1])
df = pd.DataFrame(columns=['Score', labels[0], labels[1]])
df['Score'] = data.Score.unique()
for i in labels:
df[i] = np.zeros(3)
for i in range(len(data)):
for j in range(len(labels)):
m1, m2 = labels[j].split('-') # lower & upper bounds of the age interval
if ((float(data['Age'][i])>float(m1)) & (float(data['Age'][i])<float(m2))): # find the age group in which each age lies
if data['Score'][i]==1:
index = 0
elif data['Score'][i]==2:
index = 1
elif data['Score'][i]==3:
index = 2
df[labels[j]][index] += 1
df.sort_values('Score', inplace=True)
df.set_index('Score', inplace=True)
print(df)
這產生
19.0-21.5 22.5-24.0
Score
1 2.0 2.0
2 4.0 2.0
3 3.0 9.0
是否有更好,更清潔,更有效的方法來實現這一目標?
IIUC,我認為您可以嘗試以下方法之一:
1.如果您已經知道垃圾箱:
df['Age'] = np.where(df['Age']<=21,'19-21','22-24')
df.groupby(['Age'])['Score'].value_counts().unstack()
2.如果您知道垃圾箱數量,則需要:
df.Age = pd.cut(df.Age, bins=2,include_lowest=True)
df.groupby(['Age'])['Score'].value_counts().unstack()
3. 喬恩·克萊門茨的創意評論:
pd.crosstab(pd.cut(df.Age, [19, 21, 24],include_lowest=True), df.Score)
所有這三個產生以下輸出:
Score 1 2 3
Age
(18.999, 21.0] 3 2 1
(21.0, 24.0] 2 1 3
cats = ['1', '2', '3']
bins = [0, 1, 2, 3]
data = data[['Age']].join(pd.get_dummies(pd.cut(data.Score, bins, labels=cats)))
data['bins'] = pd.cut(data['Age'], bins=[19,21,24], include_lowest=True)
data.groupby('bins').sum()
Age 1 2 3
bins
(18.999, 21.0] 117 3 2 1
(21.0, 24.0] 140 2 1 3
您可以刪除/重命名垃圾箱和年齡系列,這將需要進行一些調整才能正確包含。
我不確定您想要什么結果(您是將計數乘以分數嗎??),但這可能會有所幫助:
>>> data['age_binned'] = pd.cut(data['Age'], [18,21,24])
>>> data.groupby(['age_binned', 'Score'])['Age'].nunique().unstack()
Score 1 2 3
age_binned
(18, 21] 2 2 1
(21, 24] 2 1 1
我假設您想要唯一元素的數量,如果只想讓元素總數使用.count()而不是.nunique()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.