0

Question: Create a new column with a 1 if the country's % Renewable value is at or above the median for all countries in the top 15, and a 0 if the country's % Renewable value is below the median.

My Solution:

medi = Top15['% Renewable'].median()

if Top15['% Renewable'] >= medi:

    Top15['new col'] = 1

else:

    Top15['new col'] = 0

Top15

Error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Help: Can someone please tell me why this error is coming?Click on this link to see the dataframe

3 Answers3

0

Apply df['new column name'] = df['column name'].apply(lambda x: 'value if condition is met' if x condition else 'value if condition is not met')

0
medi = Top15['% Renewable'].median()
Top15['new col'] = Top15['% Renewable'].transform(lambda value: 1 if value>=medi else 0)
Mehul Gupta
  • 1,829
  • 3
  • 17
  • 33
  • 6
    Please don't post only code as an answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually of higher quality, and are more likely to attract upvotes. – Mark Rotteveel Mar 28 '20 at 08:18
0
medi = Top15['% Renewable'].median()
Top15['new col'] = Top15['% Renewable'].apply(lambda x:1 if x>medi else 0)
Shahir Ansari
  • 1,682
  • 15
  • 21
  • Thank you so much. But can you please explain what's wrong with my approach.? What's the fundamental error? – Eshan Kapoor Mar 28 '20 at 07:18
  • `if Top15['% Renewable'] >= medi:` This line is wrong as you are passing a column series to check instead of 1 value. To use your own method you will have a make a loop that fetches value one by one and the based on consition set the value using `Top15["new col"].iloc[position]=1/0` – Shahir Ansari Mar 28 '20 at 08:02