简体   繁体   English

如何从 python 遍历 excel 中的单元格

[英]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.具体来说,当它遍历行时,确定前 2 个单元格的平均值并将其写入第三行的单元格。

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:考虑预先计算列,使用to_stringMinMaxMean标签和 output 添加虚拟列,避免任何循环:

# 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())

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

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