【问题标题】:problem with re index dataframe (dealing with categorical data)重新索引数据框的问题(处理分类数据)
【发布时间】:2020-03-30 14:28:22
【问题描述】:

我有一个看起来像这样的数据

subject_id      hour_measure       urine color        heart_rate
3                 1                  red                40
3                 1.15               red                 60
4                  2                  yellow             50  

我想重新索引数据,以便为每位患者进行 24 小时测量 我使用以下代码

mux = pd.MultiIndex.from_product([df['subject_id'].unique(), np.arange(1,24)],
                                  names=['subject_id','hour_measure'])
df = df.groupby(['subject_id','hour_measure']).mean().reindex(mux).reset_index()
df.to_csv('totalafterreindex.csv') 

它适用于数值,但对于分类值,它会删除它, 我如何增强此代码以将均值用于数字和最常见的分类

想要的输出

 subject_id      hour_measure       urine color        heart_rate
    3                 1                  red                40
    3                 2                  red                 60
    3                 3                  yellow             50  
    3                 4                  yellow             50  
    ..                ..                ..

【问题讨论】:

  • " 但使用分类值将其删除"。 “它”是什么?
  • 我的意思是用这段代码,字符串值被删除(在我的数据集中,它删除了包含文本的列,比如尿液颜色)

标签: python python-3.x pandas scikit-learn


【解决方案1】:

想法是使用GroupBy.aggmean 用于数字和mode 用于分类,也添加nextiter 用于返回Nones 如果mode 返回空值:

mux = pd.MultiIndex.from_product([df['subject_id'].unique(), np.arange(1,24)],
                                  names=['subject_id','hour_measure'])
f = lambda x: x.mean() if np.issubdtype(x.dtype, np.number) else next(iter(x.mode()), None)
df1 = df.groupby(['subject_id','hour_measure']).agg(f).reindex(mux).reset_index()

详情

print (df.groupby(['subject_id','hour_measure']).agg(f))
                        urine color  heart_rate
subject_id hour_measure                        
3          1.00                 red          40
           1.15                 red          60
4          2.00              yellow          50

如果需要,最后根据subject_id 使用GroupBy.ffill 前向填充缺失值:

cols = df.columns.difference(['subject_id','hour_measure'])
df[cols] = df.groupby('subject_id')[cols].ffill()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 2014-10-04
    • 1970-01-01
    • 2016-06-13
    • 2020-11-13
    • 2015-09-08
    相关资源
    最近更新 更多