遍历列表并打印到Excel

时间:2019-03-09 13:55:04

标签: python excel loops

我正在尝试浏览经过过滤的Excel工作表中的行列表,并将几列中的值打印到新Excel工作表中同一列的不同行中。原始数据包含三行,我要打印到新表的五列。这是我的代码:

import xlsxwriter
import sys
import pandas as pd
import xlrd
import itertools

# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('test12.xlsx')
worksheet = workbook.add_worksheet()

# Add header line
header1 = 'Block name'
header2 = 'BlockID'
header3 = 'Key'
header4 = 'Value'
header5 = 'Unit of value'

worksheet.set_header(header1)
worksheet.set_header(header2)
worksheet.set_header(header3)
worksheet.set_header(header4)
worksheet.set_header(header5)

name = 'V_2017' 

# Read from Experiments file and filter to relevant Experiments

df2 = pd.read_excel("\Users\ingvieb\Desktop\Source_tables\Experiments.xlsx")
mask = df2['Source'].apply(lambda value: name in value)
df2 = df2[mask]

groups_exp = df2['Experiment_name']
groups_age = df2['Age']
groups_strain = df2['Strain']
groups_species = df2['Species']
groups_status = df2['Animal_status']

# Define where to find values
exp = str(df2['Experiment_name'])  
age = str(df2['Age'])
strain = str(df2['Strain'])
species = str(df2['Species'])
status = str(df2['Animal_status'])

# Define block setup

for exp, age, strain, species, status in itertools.izip(groups_exp, groups_age, groups_strain, groups_species, groups_status):

    subjectgroup = (
            ['SubjectGroup', exp, '_ID', exp, ''],
            ['SubjectGroup', exp, 'age category', age, ''],
            ['SubjectGroup', exp, 'strain', strain, ''],
            ['SubjectGroup', exp, 'species', species, ''],
            ['SubjectGroup', exp, 'disability/disease', status, '']
            )
    

### Write out excel sheet

# Start from the first cell. Rows and columns are zero indexed.
row = 0
col = 0

# Iterate over the data and write it out row by row.
worksheet.write(row, col, header1)
worksheet.write(row, col +1, header2)
worksheet.write(row, col +2, header3)
worksheet.write(row, col +3, header4)
worksheet.write(row, col +4, header5)

row = 1
col = 0

for exp, age, strain, species, status in itertools.izip(groups_exp, groups_age, groups_strain, groups_species, groups_status):
    
        for blockname, blockID, key, value, unit in (subjectgroup):
            worksheet.write(row, col,     blockname)
            worksheet.write(row, col + 1, blockID)
            worksheet.write(row, col +2, key)
            worksheet.write(row, col +3, value)
            worksheet.write(row, col +4, unit)
            row += 1
       
        
    
        
workbook.close()

在输出表中,我得到了正确的行数(是感兴趣的五列的三倍),但是在所有行中我只得到了相同的数据。这些都是来自其中一行的数据,重复了三遍。该代码是否只经过我的一行之一,如果可以,为什么?

这是我第一次尝试编写代码。我正在使用Python 2.7。

0 个答案:

没有答案