简体   繁体   中英

How to iterate through cells in excel from python

I want to write the average between two columns(Max and Min) into another column(Mean) for each row. Specifically, as it iterates through rows, determine the mean from first 2 cells and write this into the cell of the 3rd row.

import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile

sheet._cell_overwrite_ok = True 

df = pd.read_excel('tempMean.xlsx', sheet_name='tempMeanSheet')

listMax = df['Max']
listMin = df['Min']
listMean = df['Mean']

for df, row in df.iterrows():
    print('Max', row.Max, 'Min', row.Min, 'Mean', row.Mean)

Current Results:

Max 29.7 Min 20.5 Mean nan
Max 29.2 Min 20.2 Mean nan
Max 29.1 Min 21.2 Mean nan

Results I want:

Max 29.7 Min 20.5 Mean 24.95
Max 29.2 Min 20.2 Mean 24.7
Max 29.1 Min 21.2 Mean 25.15

I have been able to iterate through rows as seen in code. However, I am not sure how to apply the equation to find mean for each of these rows. Consequently, the row for mean has no data.

Let me know if anything doesnt make sense

Try this:

df = pd.read_excel('tempMean.xlsx', sheet_name='tempMeanSheet')
mean = [(row["Min"] + row["Max"]) / 2 for index, row in df.iterrows()]
df = df.assign(Mean=mean)

Consider calculating column beforehand, add dummy columns for your Min , Max , Mean labels and output with to_string , avoiding any loops:

# VECTORIZED CALCULATION OF MEAN
df['Mean'] = (df['Max'] + df['Min']) / 2

# ADD LABEL COLUMNS AND RE-ORDER COLUMNS
df = (df.assign(MaxLabel='Max', MinLabel='Min', MeanLabel='Mean')
        .reindex(['MaxLabel', 'Max', 'MinLabel', 'Min', 'MeanLabel', 'Mean'], axis='columns')
      )

# OUTPUT TO SCREEN IN ONE CALL
print(df.to_string())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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