0

I would need help saving the values my for-loop iterates over.

With this script I create my csv the way I need it, but there is no information what value w and c has in each row. How can I add this information in two more columns?

import pandas as pd

df = pd.read_csv(...)

country_list = df.Country.unique()
wave_list = df.Wave.unique()

dn = pd.DataFrame()

for w in wave_list:
    print ("Wave is: " + str(w))
    wave_select =df[df["Wave"] == w] # Select Rows for Waves
    for c in country_list:
        print ("Country is: " + str(c))
        country_select = df[df["Country"] == c] # Select Rows for Countries
        out = country_select["Sea"].value_counts(normalize=True)*100 # Calculate Percentage
        print (out)
        dn = dn.append(out)
dn.to_csv (...)

I would be very grateful for help.

1
  • 3
    Please add some example input data and add the expected result to make it easier to help you Commented Nov 22, 2020 at 11:43

1 Answer 1

2

Before loop: dn = pd.DataFrame(columns=['wave','country','out'])

Inside inner loop instead of dn = dn.append(out):

dn = dn.append({'wave':w,'country':c,'out':out}, ignore_index=True)
Sign up to request clarification or add additional context in comments.

4 Comments

Should be the expected answer
Thank you, that is exactly what I was looking for! :)
As I look at the saved csv I still see something is wrong. Only the last set of calculation is stored. I have the same results for all waves.
The inner loop makes exactly the same calculations for every wave. Maybe you should use wave_select in the inner loop.

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.