0

I have a very simple for loop which was working last week but when I run it this week on exactly the same data it is not working... when I run the code outside of the loop it works without an error. I don't understand...

The code is: '''

survey = pd.read_csv(folderin + 'survey.csv')
CSsurvey = pd.read_csv(folderin + 'CS_survey.csv')

sports = ['Value MTB related (e.g. inner tubes, water bottles etc)',
'Value Running','Value Roaming and other outdoor related (e.g. climbing, kayaking)',
'Value Outdoor sports event related (e.g.race)']

sport = []
for p in sports:
    item = survey[p].sum()
    CSitem = CSsurvey[p].sum()
    total = item + CSitem
    sport.append(total)'''

I get the error:

enter image description here enter image description here

If I run the code for each 'p' outside of the loop I don't get an error

5
  • what does the data look like? have you confirmed that the column headers you iterate through exist in each data frame? if you cannot be sure at run time you can add logic to check if that column header exists before attempting to index Commented Mar 24 at 15:37
  • I have copied and pasted each of the strings in sports = [] and run the code with these. No issue at all. Commented Mar 24 at 15:43
  • Seems like the solution is to close spyder and reopen it... lets see if it still works tomorrow.... Commented Mar 24 at 16:16
  • 1
    sport = pd.concat([survey, CSurvey]).sum(axis=0)[sports].to_list() Commented Mar 24 at 20:27
  • Thanks @ScottBoston I knew there was an easier way for me to do this but hadn't realised you could concat with a specific set of columns. Awesome. Commented Mar 25 at 8:44

1 Answer 1

1

IIUC then you can rewrite the above for loop using pd.concat and then taking the sum over all columns and using column filtering to return on the sports columns finally add to_list to convert those sums to a list.

Try:

sport = pd.concat([survey, CSurvey]).sum(axis=0)[sports].to_list()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.