迭代csv / xlsx文件python 3中的行和列

时间:2017-05-04 09:26:19

标签: python excel csv pandas

我是Stack Overflow的新手,遇到了一个我无法解决的问题。 我有一个csv文件或excel(基本上是一个表),并希望在Python 3中执行以下操作:

Column Header,"r269_d","r295_A","r295_R","r299_A","r325_D","r326_A"

id1,"0.0","2.29","0.0","1.3","0.0","188.4"

id2,"0.0","1.0","0.0","0.6","0.0","0.0"

对于这个csv文件,我想:

  1. 进入第一行(id1)

  2. 检查第1列(r269_d)

    2.1如果col1 = 0的值将0写入新的result_string

    2.2如果col1!= 0的值将1写入新的result_string

  3. 检查第2列(r295_A)

    3.1如果col2 = 0的值将0写入与2.1

    中提到的相同的result_string

    3.2如果col2!= 0的值将1写入2.1中提到的相同result_string

  4. 为所有列执行此操作

  5. 转到下一行并执行相同操作。

  6. 最后我希望看到这样的东西:

    Column Header,"r269_d","r295_A","r295_R","r299_A","r325_D","r326_A", "result_string"
    
    id1,"0.0","2.29","0.0","1.3","0.0","188.4","010101"
    
    id2,"0.0","1.0","0.0","0.6","0.0","0.0","010100"
    

1 个答案:

答案 0 :(得分:1)

熊猫解决方案:

import pandas as pd
import numpy as np

df = pd.read_csv(r'/path/to/file.csv')

df['result_string'] = (df.filter(regex='r\d+')
                         .ne(0).astype(np.int8).astype(str)
                         .apply(''.join, axis=1))

df.to_csv(r'/path/to/result.csv', index=False)

源CSV文件:

col,r269_d,r295_A,r295_R,r299_A,r325_D,r326_A
id1,0.0,2.29,0.0,1.3,0.0,188.4
id2,0.0,1.0,0.0,0.6,0.0,0.0

解析DF:

In [169]: df
Out[169]:
   col  r269_d  r295_A  r295_R  r299_A  r325_D  r326_A
0  id1     0.0    2.29     0.0     1.3     0.0   188.4
1  id2     0.0    1.00     0.0     0.6     0.0     0.0

结果:

In [170]: df['result_string'] = (df.filter(regex='r\d+')
     ...:                          .ne(0).astype(np.int8).astype(str)
     ...:                          .apply(''.join, axis=1))
     ...:

In [171]: df
Out[171]:
   col  r269_d  r295_A  r295_R  r299_A  r325_D  r326_A result_string
0  id1     0.0    2.29     0.0     1.3     0.0   188.4        010101
1  id2     0.0    1.00     0.0     0.6     0.0     0.0        010100

In [172]: df.to_csv(r'c:/temp/result.csv', index=False)

产生的CSV:

col,r269_d,r295_A,r295_R,r299_A,r325_D,r326_A,result_string
id1,0.0,2.29,0.0,1.3,0.0,188.4,010101
id2,0.0,1.0,0.0,0.6,0.0,0.0,010100