将pandas iterrows的输出写入文件中

2024-10-02 02:26:47 发布

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

两个数据帧

df1:

ch  start   end strand  5ss 3ss
3   90280167    90280927    +   90280167    90280927
3   90280167    90281242    +   90280167    90281242
3   90280986    90281242    +   90280986    90281242
3   90281284    90284526    +   90281284    90284526
5   33977824    33984550    -   33984550    33977824

df2:

^{pr2}$

代码:

c1 = []
c = 0 
for ii,rr in df1.iterrows():
    c1.append(rr)


c2 = []
with open('3prime.txt', 'w') as w:  
     for i,r in df2.iterrows():
         c2.append(r)
     for i in c1:
         for j in c2:
             start = int(1[4])
             end = int(i[5])
             fivep = int(j[4])
             threep = int(j[5])

             if start == fivep:
                print i

输出:

ch                                      3
start                            90280167
end                              90280927
strand                                  +
5ss                              90280167
3ss                              90280927
ch                                      5
start                            33983577
end                              33984550
strand                                  -
5ss                              33984550
3ss                              33983577

期望输出:

ch  start   end strand  5ss 3ss
3   90280167    90281242    +   90280167    90281242 #from df1
3   90280167    90281242    +   90280167    90281242 # fromdf2
5   33977824    33984550    -   33984550    33977824 # fromdf1
5   33977824    33984550    -   33984550    33977824 #fromdf2

问题1:当我试图写入文件时,我会得到一个空白文件,其次,我也想这样做if start == fivep:是真的

打印i和下一行打印j

像这样的东西

print i +'\n' + j
TypeError: unsupported operand type(s) for +: 'float' and 'str'

那我试试这个

print str(i) + '\n' + str(j)

这意味着df1中第一行匹配,df2第二行匹配

当我尝试第二个print语句时,我得到的输出与第一个print语句(print i)相同,但是现在使用j的元素,有人能指导我如何处理这个问题吗。在


Tags: inforrrchstartintenddf1
1条回答
网友
1楼 · 发布于 2024-10-02 02:26:47

为什么不跳过使用iterrows方法是构建所需的数据帧,然后用df.to_csv('desired/path/to/file.csv')保存它?在

例如,用我理解的作为你的标准,比如

out1 = df1.merge(df2, on='5ss', suffixes=['', '_y'])[df1.columns]
out2 = df2.merge(df1, on='5ss', suffixes=['', '_y'])[df2.columns]
pd.concat(out1, out2).sort_index().to_csv('3prime.txt')

应该做你想做的。在

相关问题 更多 >

    热门问题