我有一个数据集[0,1,1,2],我想聚合它。 为此,我必须计算并将“频率”:1/4手动放入数据帧。这是密码。
>>> df = pd.DataFrame({'value':[0, 1, 1, 2], ... 'frequency':1/4}) >>> df.groupby('value').sum() frequency value 0 0.25 1 0.50 2 0.25
有没有一种更有效的方法可以在python或r中聚合数据集并自动计算频率?
如果不使用熊猫,你可以使用柜台
from collections import Counter z = [0,1,1,2] Counter(z) Counter({1: 2, 0: 1, 2: 1})
然后到一个数据帧
x = Counter(z) df = pd.DataFrame.from_dict(x, orient='index').reset_index()
然后取值除以4(你想要的频率)
在 R 你可以做点什么
R
library(data.table) dt <- data.table(sample(0:2,100,replace=TRUE)) dt[,.N/nrow(dt),V1] ## > dt[,.N/nrow(dt),V1] ## V1 V1 ## 1: 1 0.33 ## 2: 2 0.32 ## 3: 0 0.35
在R
prop.table(table(dat$value)) 0 1 2 0.25 0.50 0.25
在巨蟒中,麻木
import numpy as np u,c=np.unique(df.value,return_counts=True) pd.Series(c/c.sum(),index=u) 0 0.25 1 0.50 2 0.25 dtype: float64
df['value'].value_counts(normalize=True,sort=False)
也许你可以试试这个…
参考:
import pandas as pd pd.Series([0, 1, 1, 2]).value_counts(normalize=True, sort=False)