简体   繁体   中英

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. The destination column gets made but then the information from the for loop doesn't print into the excel file.

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.
You should use return "Final Round" and return "cut" .

But with pandas you should rather use its functions instead of for -loop - ie. 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

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?' with default value 'cut' and later filter rows in which you want to set '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)

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