Pandas:将具有重复行名称的数据重塑为列

4

我有一个数据集,类似于这个(仅显示前几行):

Sample  Detector        Cq
P_1   106    23.53152
P_1   106    23.152458
P_1   106    23.685083
P_1   135        24.465698
P_1   135        23.86892
P_1   135        23.723469
P_1   17  22.524242
P_1   17  20.658733
P_1   17  21.146122

"样本"和"检测器"列均包含重复值("Cq"是唯一的):确切地说,每个"检测器"在数据中都出现3次,因为它是数据中的一个副本。

我需要做的是:

  • 重新调整表格,使列包含样本,行包含检测器
  • 重命名重复的列,以便我知道哪个是副本

我认为DataFrame.pivot可以解决问题,但它因为有重复数据而失败了。什么是最好的方法?重命名重复项,然后进行重塑,还是有更好的选择?

编辑:我考虑过后,认为最好阐明目的。我需要为每个“样本”存储其“检测器”的平均值和标准差。

1个回答

5

看起来您可能需要的是分层索引数据框架【链接】

这样的内容是否满足您的需求?

#build a sample dataframe
a=['P_1']*9
b=[106,106,106,135,135,135,17,17,17]
c = np.random.randint(1,100,9)
df = pandas.DataFrame(data=zip(a,b,c), columns=['sample','detector','cq'])

#add a repetition number column
df['rep_num']=[1,2,3]*( len(df)/3 )

#Convert to a multi-indexed DF
df_multi = df.set_index(['sample','detector','rep_num'])

#--------------Resulting Dataframe---------------------

                             cq
sample detector rep_num    
P_1    106      1        97
                2        83
                3        81
       135      1        46
                2        92
                3        89
       17       1        58
                2        26
                3        75

如何从这个数据中基于 max(cq) 选择 sample?\n 假设生成一个新的 df:\n sample detector rep_num cq\n p_1 106 1 97 - EKivutha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接