运行pandas iterrorws时/之后,如何将索引位置保留回输出?

2024-06-16 10:47:40 发布

您现在位置:Python中文网/ 问答频道 /正文

在以下数据框中:

d1 = pd.read_csv('to_count.mcve.txt', sep='\t')
d1 = d1.set_index(['pos'], append=True)

       M1           M2       F1   F2
  pos                        
0 23   A,B,A,C,D    A,C,B    A    D
1 24   A,B,B,C,B    A,B,A    B    B
2 28   C,B,C,D,E    B,C      E    C

我使用以下代码进行了一些计数:

hapX_count = pd.DataFrame()
hapY_count = pd.DataFrame()
for index, lines in d1.iterrows():
    hap_x = lines['F1']
    hap_y = lines['F2']
    x_count = lines.apply(lambda x: x.count(hap_x)/2 if len(x) > 5 else x.count(hap_x))
    y_count = lines.apply(lambda x: x.count(hap_y)/2 if len(x) > 5 else x.count(hap_y))

    hapX_count = hapX_count.append(x_count)
    hapY_count = hapY_count.append(y_count)


print(hapX_count)

输出为:

         F1   F2   M1   M2
(0, 23)  1.0  0.0  1.0  1.0
(1, 24)  1.0  1.0  1.5  1.0
(2, 28)  1.0  0.0  0.5  0.0

如何将索引值(pos)恢复到以前数据中的状态?我可以使用索引调用这些元组的位置。但是,我想自动化这个过程,以便保留所有索引,因为在我的原始数据中将有多个索引(不仅仅是pos

谢谢


Tags: 数据posindexcountf2f1d1pd
1条回答
网友
1楼 · 发布于 2024-06-16 10:47:40

可以用下面的行替换for循环上方的两行。这将创建空数据帧,其索引与d1的索引具有相同的名称

hapX_count = pd.DataFrame(index=d1.index[0:0])
hapY_count = pd.DataFrame(index=d1.index[0:0])

相关问题 更多 >