Python pandas.cut

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31416684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:37:26  来源:igfitidea点击:

Python pandas.cut

pythonpandas

提问by j riot

Edit: Added defT

编辑:添加 defT

Does using pandas.cutchange the structure of a pandas.DataFrame.

using 是否会pandas.cut更改pandas.DataFrame.

I am using pandas.cutin the following manner to map single age years to age groups and then aggregating afterwards. However, the aggregation does not work as I end up with NaNin all columns that are being aggregated. Here is my code:

我使用pandas.cut以下方式将单个年龄年份映射到年龄组,然后进行聚合。但是,聚合不起作用,因为我最终NaN在所有被聚合的列中。这是我的代码:

cutoff = numpy.hstack([numpy.array(defT.MinAge[0]),   defT.MaxAge.values])
labels = defT.AgeGrp

df['ageGrp'] = pandas.cut(df.Age, 
                          bins              = cutoff, 
                          labels            = labels, 
                          include_lowest    = True)

Here is defT:

这是defT:

AgeGrp  MaxAge  MinAge
   1      18      14
   2      21      19
   3      24      22
   4      34      25
   5      44      35
   6      54      45
   7      65      55

Then I pass the data-frame into another function to aggregate:

然后我将数据帧传递给另一个函数进行聚合:

grouped = df.groupby(['Year', 'Month', 'OccID', 'ageGrp', 'Sex', \
                      'Race', 'Hisp', 'Educ'], 
                      as_index = False)

final   = grouped.aggregate(numpy.sum)

If I change the ages to age groups via this manner it works perfectly:

如果我通过这种方式将年龄更改为年龄组,它可以完美地工作:

df['ageGrp'] = 1
df.ix[(df.Age >= 14) & (df.Age <= 18), 'ageGrp'] = 1 # Age 16 - 20
df.ix[(df.Age >= 19) & (df.Age <= 21), 'ageGrp'] = 2 # Age 21 - 25  
df.ix[(df.Age >= 22) & (df.Age <= 24), 'ageGrp'] = 3 # Age 26 - 44  
df.ix[(df.Age >= 25) & (df.Age <= 34), 'ageGrp'] = 4 # Age 45 - 64  
df.ix[(df.Age >= 35) & (df.Age <= 44), 'ageGrp'] = 5 # Age 64 - 85  
df.ix[(df.Age >= 45) & (df.Age <= 54), 'ageGrp'] = 6 # Age 64 - 85  
df.ix[(df.Age >= 55) & (df.Age <= 64), 'ageGrp'] = 7 # Age 64 - 85  
df.ix[df.Age >= 65, 'ageGrp'] = 8 # Age 85+

I would prefer to do this on the fly, importing the definition table and using pandas.cut, instead of being hard-coded.

我更愿意即时执行此操作,导入定义表并使用pandas.cut,而不是进行硬编码。

Thank you in advance.

先感谢您。

采纳答案by unutbu

Here is, perhaps, a work-around.

这也许是一种解决方法。

Consider the following example which replicates the symptom you describe:

考虑以下示例,该示例复制了您描述的症状:

import numpy as np
import pandas as pd
np.random.seed(2015)

defT = pd.DataFrame({'AgeGrp': [1, 2, 3, 4, 5, 6, 7],
                     'MaxAge': [18, 21, 24, 34, 44, 54, 65],
                     'MinAge': [14, 19, 22, 25, 35, 45, 55]})

cutoff = np.hstack([np.array(defT['MinAge'][0]), defT['MaxAge'].values])
labels = defT['AgeGrp']

N = 50
df = pd.DataFrame(np.random.randint(100, size=(N,2)), columns=['Age', 'Year'])
df['ageGrp'] = pd.cut(df['Age'], bins=cutoff, labels=labels, include_lowest=True)

grouped = df.groupby(['Year', 'ageGrp'], as_index=False)
final = grouped.agg(np.sum)
print(final)
#              Year  ageGrp  Age
# Year ageGrp                   
# 3    1        NaN     NaN  NaN
#      2        NaN     NaN  NaN
# ...
# 97   1        NaN     NaN  NaN
#      2        NaN     NaN  NaN
# [294 rows x 3 columns]

If we change

如果我们改变

grouped = df.groupby(['Year', 'ageGrp'], as_index=False)
final = grouped.agg(np.sum)

to

grouped = df.groupby(['Year', 'ageGrp'], as_index=True)
final = grouped.agg(np.sum).dropna()
print(final)

then we obtain:

然后我们得到:

             Age
Year ageGrp     
6    7        61
16   4        32
18   1        34
25   3        23
28   5        39
34   7        60
35   5        42
38   4        25
40   2        19
53   7        59
56   4        25
     5        35
66   6        54
67   7        55
70   7        56
73   6        51
80   5        36
81   6        46
85   5        38
90   7        58
97   1        18