8. 当多个变量被存储为列名时进行清理

  1. # 读取weightlifting数据集
  2. In[57]:weightlifting = pd.read_csv('data/weightlifting_men.csv')
  3. weightlifting
  4. out[57]:

8. 当多个变量被存储为列名时进行清理 - 图1

  1. # 用melt方法,将sex_age放入一个单独的列
  2. In[58]:wl_melt = weightlifting.melt(id_vars='Weight Category',
  3. var_name='sex_age',
  4. value_name='Qual Total')
  5. wl_melt.head()
  6. out[58]:

8. 当多个变量被存储为列名时进行清理 - 图2

  1. # 用split方法将sex_age列分为两列
  2. In[59]:sex_age = wl_melt['sex_age'].str.split(expand=True)
  3. sex_age.head()
  4. out[59]: 0 1
  5. 0 M35 35-39
  6. 1 M35 35-39
  7. 2 M35 35-39
  8. 3 M35 35-39
  9. 4 M35 35-39
  1. # 给列起名
  2. In[60]:sex_age.columns = ['Sex', 'Age Group']
  3. sex_age.head()
  4. out[60]:

8. 当多个变量被存储为列名时进行清理 - 图3

  1. # 只取出字符串中的M
  2. In[61]:sex_age['Sex'] = sex_age['Sex'].str[0]
  3. sex_age.head()
  4. out[61]:

8. 当多个变量被存储为列名时进行清理 - 图4

  1. # 用concat方法,将sex_age,与wl_cat_total连接起来
  2. In[62]:wl_cat_total = wl_melt[['Weight Category', 'Qual Total']]
  3. wl_tidy = pd.concat([sex_age, wl_cat_total], axis='columns')
  4. wl_tidy.head()
  5. out[62]:

8. 当多个变量被存储为列名时进行清理 - 图5

  1. # 上面的结果也可以如下实现
  2. In[63]:cols = ['Weight Category', 'Qual Total']
  3. sex_age[cols] = wl_melt[cols]

更多

  1. # 也可以通过assign的方法,动态加载新的列
  2. In[64]: age_group = wl_melt.sex_age.str.extract('(\d{2}[-+](?:\d{2})?)', expand=False)
  3. sex = wl_melt.sex_age.str[0]
  4. new_cols = {'Sex':sex,
  5. 'Age Group': age_group}
  6. In[65]: wl_tidy2 = wl_melt.assign(**new_cols).drop('sex_age', axis='columns')
  7. wl_tidy2.head()
  8. out[65]:

8. 当多个变量被存储为列名时进行清理 - 图6

  1. # 判断两种方法是否等效
  2. In[66]: wl_tidy2.sort_index(axis=1).equals(wl_tidy.sort_index(axis=1))
  3. out[66]: True