2017-10-08 74 views
1

我有一个我希望根据频率进行分类的城市名称列表。我首先想要使用binning,但是因为这需要单调的间距,所以我放弃了这一点。接下来,甚至更好的方法是使用pandas.qcut根据频率创建基于分位数的类别。但拥有分位数,我不知道如何根据分位数创建一个额外的列。例如:如何根据频率对文本列进行分类

import numpy as np 
import pandas as pd 

np.random.seed(0) 
cities = np.random.choice(['Ontario', 'Ottawa', 'Vancouver','Edmonton', 
          'Winnipeg', 'Churchill'], 500) 
# Create fake data and their frequencies 
df = pd.DataFrame (cities, columns=['City']) 
freq = df['City'].value_counts() 
print (freq) 
# Create quantiles 
qc = pd.qcut (freq, 3) 
print (qc) 
# And now? I have the quantiles but how to assign a categorie to each City? 
category_for_each_city = df['City'] in qC# does not work, but many other things neither 

我尝试了很多事情,但都没有成功。我应该能够为此编写一个循环,但我无法想象这是Python的方式。我试图寻找一些sklearn变形金刚,但无法找到任何与此特定的解决方案。任何帮助将不胜感激。

此外,我有很多倾斜的分布,可以扩展到例如日志转换的解决方案将有很大的帮助。

回答

1

你几乎没有...

In [106]: category_for_each_city = df['City'].map(qc) 

In [107]: category_for_each_city 
Out[107]: 
0  (77.333, 84.667] 
1  (72.999, 77.333] 
2  (84.667, 100.0] 
3  (84.667, 100.0] 
4  (84.667, 100.0] 
5  (84.667, 100.0] 
6  (77.333, 84.667] 
      ... 
493  (84.667, 100.0] 
494 (72.999, 77.333] 
495 (77.333, 84.667] 
496  (84.667, 100.0] 
497 (77.333, 84.667] 
498 (77.333, 84.667] 
499 (77.333, 84.667] 
Name: City, Length: 500, dtype: category 
Categories (3, interval[float64]): [(72.999, 77.333] < (77.333, 84.667] < (84.667, 100.0]] 

UPDATE:

In [114]: qc = pd.qcut (freq, 3, labels=[0,1,2]) 

In [115]: category_for_each_city = df['City'].map(qc) 

In [116]: category_for_each_city 
Out[116]: 
0  1 
1  0 
2  2 
3  2 
4  2 
5  2 
6  1 
     .. 
493 2 
494 0 
495 1 
496 2 
497 1 
498 1 
499 1 
Name: City, Length: 500, dtype: category 
Categories (3, int64): [0 < 1 < 2] 
+0

这很容易的确。我正在尝试类似'qc.category_for_each_city.codes [df ['City']]',但您的解决方案要简单得多。非常感谢你的帮助! – Arnold

相关问题