Python Pandas .cut

标签 python pandas

编辑:添加 defT

使用 pandas.cut 是否会改变 pandas.DataFrame 的结构。

我按以下方式使用 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)

这是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

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

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

final   = grouped.aggregate(numpy.sum)

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

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+

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

提前致谢。

最佳答案

这也许是一种解决方法。

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

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]

如果我们改变

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

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

然后我们得到:

             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

关于Python Pandas .cut,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31416684/

相关文章:

python - 是什么导致 Pandas 出现 "indexing past lexsort depth"警告?

python - 如何在python中制作函数列表?

python - Pandas 在一个月内重新采样到特定的工作日

python - 在值(value)条件下,有没有更快的方法来计算带有 pandas 的 groupby 对象的历史比率?

python - Pandas groupby 聚合忽略空白或无值

python - 检查记录是否存在于 MongoDB 中

python - 将定义集中的值设置为 pandas 数据框中列的给定值(例如 NaN)

python - 如果 pandas 系列中的字符串包含来自另一个 pandas 数据帧的字符串

python - Pandas 合并 300 个数据帧

python - Pandas : Replace old column values and plot new column values with respect to equations