使用Pandas创建/重命名类别

时间:2017-06-01 18:29:19

标签: python python-2.7 pandas

我正在使用pandas(python 2.7)使用(部分)以下代码评估调查:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

首先阅读.csv

df = pd.read_csv("data_project_638595_2017_05_23.csv", sep=';',usecols=range(6,82) + range(92,112))

重命名列(这是一个示例):

df.rename(columns={"v_27" : "age"}, inplace=True)

为所有示例设置数据类型(这是一个示例):

df["age"] = df["age"].astype("category")

年龄也被问及参与者的调查。因此现在年龄确实如此,其中2.0 =“20-29岁”:

df.age

       age
...
333    2.0
336    2.0
338    2.0
Name: age, dtype: category
Categories (5, float64): [1.0, 2.0, 3.0, 4.0, 5.0]

它的数量如下:

df.age.value_counts()

2.0    178
3.0     29
5.0      3
4.0      2
1.0      2
Name: age, dtype: int64

我现在想要做的是建立并重命名以下类别(这也意味着,“60 +”有0个计数,类别也应该被订购):

['0-19', '20-29', '30-39', '40-49', '50-59', '60+']

我尝试了几种方法(例如rename_categories),但我无法让它像它应该的那样工作。

对此有什么可行的解决方案?提前谢谢!

1 个答案:

答案 0 :(得分:0)

使用pd.cut方法:

df['new'] = pd.cut(df.age, 
                   bins=[0, 19, 29, 39, 49, 59, 999], 
                   labels=['0-19', '20-29', '30-39', '40-49', '50-59', '60+'],
                   include_lowest=True)

演示:

In [103]: df = pd.DataFrame(np.random.randint(100, size=(10)), columns=['age'])

In [104]: df
Out[104]:
   age
0   10
1   64
2   84
3   14
4    4
5   31
6   98
7   22
8   49
9   50

In [105]: df['new'] = pd.cut(df.age,
     ...:                    bins=[0, 19, 29, 39, 49, 59, 999],
     ...:                    labels=['0-19', '20-29', '30-39', '40-49', '50-59', '60+'],
     ...:                    include_lowest=True)

In [106]: df
Out[106]:
   age    new
0   10   0-19
1   64    60+
2   84    60+
3   14   0-19
4    4   0-19
5   31  30-39
6   98    60+
7   22  20-29
8   49  40-49
9   50  50-59

<强>更新

映射:

In [20]: d
Out[20]: {0: '0-19', 1: '20-29', 2: '30-39', 3: '40-49', 4: '50-59', 5: '60+'}

来源DF:

In [21]: df
Out[21]:
   age
0    0
1    3
2    2
3    3
4    4
5    2
6    0
7    3
8    2
9    4

映射年龄:

In [22]: df.age.map(d)
Out[22]:
0     0-19
1    40-49
2    30-39
3    40-49
4    50-59
5    30-39
6     0-19
7    40-49
8    30-39
9    50-59
Name: age, dtype: object