【问题标题】:Converting data to matrix by group in Python在Python中按组将数据转换为矩阵
【发布时间】:2021-01-29 19:07:02
【问题描述】:

我想为我的数据集中的每个观察创建矩阵。 每行应对应于疾病组(即 xx、yy、kk)。示例数据

id  xx_z xx_y xx_a yy_b yy_c kk_t kk_r kk_m kk_y
1    1    1    0    0     1   0     0    1   1
2    0    0    1    0     0   1     1    0   1 

假设有 3 种疾病,数据集中最多有 4 种疾病。矩阵应为 3 X 4,输出应如下所示:

       id       matrix           
              xx_z xx_y  xx_a null 
        1   xx [ 1    1    0    0 
               yy_b  yy_c  null null
            yy   0    1    0    0
                kk_t kk_r kk_k  kk_y
            kk   0    0    1    1]

      2       [ 0 0 1 0
              0 0 0 0
              1 1 0 1]

请注意,我不知道每个疾病组的确切疾病数量。我怎么能在 python pandas 中做到这一点?

附:我只需要每个观察的嵌套矩阵结构,稍后我将比较不同观察的矩阵,例如观察 id == 1 和观察 id == 2 的矩阵的 Jaccard 相似度

【问题讨论】:

  • 你能把矩阵放在你想要 xx_z 等去的地方吗?我无法从您的描述中弄清楚如何将顶部代码块中的数字排列到底部代码块中的数字中
  • 当然让我来做
  • kk_m 去哪儿了?仅仅是第一个 xx 转到第一个项目等...
  • 是的,完全正确。我实际上想计算不同物种的疾病相似性,但我需要一种嵌套矩阵结构。但问题是每种疾病可能有不同数量的亚型......

标签: python pandas numpy


【解决方案1】:

好的,这样的事情怎么样:

# make a copy just in case
d = df[:]

# get the groups, in case you don't have them already
groups = list({col.split('_')[0] for col in d.columns})

# define grouping condition (here, groups would be 'xx', 'yy', 'kk')
gb = d.groupby(d.columns.map(lambda x: x.split('_')[0]), axis=1) 

# aggregate values of one group to list and save as extra columns
for g in groups:
   d[g] = gb.get_group(g).values.tolist()

# now aggregate to list of lists
d['matrix'] = d[groups].values.tolist()

# convert list of lists to a matrix
d['matrix'] = d['matrix'].apply(lambda x: pd.DataFrame.from_records(x).fillna(0).astype(int).values)

# for the desired output
d[['matrix']]

不是最优雅的,但我希望它能完成工作:)

【讨论】:

    猜你喜欢
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多