简体   繁体   English

如何将python for循环的输出插入excel列?

[英]How to insert output of a python for loop into an excel column?

I'm trying to use a for loop to populate data in a destination column in an excel spreadsheet.我正在尝试使用 for 循环在 Excel 电子表格的目标列中填充数据。 The destination column gets made but then the information from the for loop doesn't print into the excel file.目标列已生成,但来自 for 循环的信息不会打印到 excel 文件中。

import pandas as pd
aasb_scores = pd.read_excel ('/Users/nnamdiokoli/Library/Containers/com.microsoft.Excel/Data/Desktop/AASB Scoring PivotTable Example.xlsx', 
                             index=False) 

aasb_scores['Average'] = (aasb_scores['Q1'] + 
           aasb_scores['Q2']+ aasb_scores['Q3'] + 
           aasb_scores['Q4'] + aasb_scores['Q5'])/5.00
aasb_scores.head(10)

def finalround():
    for i in aasb_scores['Average']:
        if i >= 3:
            print('Final Round')
        else:
            print('cut')

aasb_scores['Moving on?'] = finalround()

aasb_scores.to_excel('/Users/nnamdiokoli/Library/Containers/com.microsoft.Excel/Data/Desktop/AASB Scoring PivotTable Example.xlsx',
                     index=False)

print() is used only to display on screen, not to put in variable or any other place. print()仅用于在屏幕上显示,而不用于放入变量或任何其他地方。
You should use return "Final Round" and return "cut" .您应该使用return "Final Round"return "cut"

But with pandas you should rather use its functions instead of for -loop - ie.但是对于pandas你应该使用它的函数而不是for -loop - 即。 apply() . apply()

import pandas as pd
import random

df = pd.DataFrame({'Average': [random.randint(0,5) for _ in range(10)]})

def finalround(value):
    if value >= 3:
       return 'Final Round'
    else:
       return 'cut'

df['Moving on?'] = df['Average'].apply(finalround)

print(df)

or shorter with lambda或更短的lambda

import pandas as pd
import random

df = pd.DataFrame({'Average': [random.randint(0,5) for _ in range(10)]})

df['Moving on?'] = df['Average'].apply(lambda x: 'Final Round' if x>=3 else 'cut')

print(df)

Eventually you can create column 'Moving on?'最终您可以创建列'Moving on?' with default value 'cut' and later filter rows in which you want to set 'Final Round'使用默认值'cut'和稍后过滤要在其中设置'Final Round'

import pandas as pd
import random

df = pd.DataFrame({'Average': [random.randint(0,5) for _ in range(10)]})

df['Moving on?'] = 'cut'

df['Moving on?'][ df['Average'] >= 3 ] = 'Final Round'

print(df)

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

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