繁体   English   中英

如何合并来自同一行和列索引/值的两个熊猫数据框的值?

[英]How can I merge the values from two pandas dataframe which as same row and column indexes/value?

在以下熊猫数据框中:

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)

hapX_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

hapY_count的输出:

print(hapY_count)

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

如何将这些数据框中的值(具有相同的columnrow索引)与逗号合并?

预期输出如下:

         F1       F2       M1       M2
(0, 23)  1.0,0.0  0.0,1.0  1.0,0.5  1.0,0.0
same for other lines...

谢谢,

您可以继续并在for循环内进行串联。 但是,如果您打算在事后进行串联并希望它们之间用逗号分隔,那么我认为您可以将数据变成字符串而不是浮点数。 如果是这样,并且您知道列和索引相同且顺序相同,则可以执行以下操作:

df = hapX_count.astype(str) + ',' + hapY_count.astype(str)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM