-2

I would like to write a def function that gives me these values when working with the dataframe. It shows amount of bikers in each country for a specific year. It is indexed by country code.

The dataframe name is df3_merged

The first 2 lines of dataframe looks like this: Columns are Country name and different years as columns.

             Country Name     1960      1970      1980  
Country Code
   AGO          Angola         500      1000      1400
   ZAM          Zambia         600      3304      6009



def pop_bikers(country_name, year):
      #code here
     return 


When input is pop_bikers('Zambia', 1970) == Answer: 3304

I would just like to know how can write this def function to get the answer of 3304.

There is alot of countries and alot of years, just curious as to how one would write it in a def function.

Back Buddy
  • 35
  • 7
  • There are some fantastic documentation sets and advice pages for getting this detail - Maybe start here ? https://towardsdatascience.com/pandas-equivalent-of-10-useful-sql-queries-f79428e60bd9 – irnerd Mar 30 '21 at 14:00
  • You can also try to use filter based on multiple columns https://stackoverflow.com/questions/22086116/how-do-you-filter-pandas-dataframes-by-multiple-columns – pratap Mar 30 '21 at 14:03
  • https://pandas.pydata.org/docs/user_guide/indexing.html – wwii Mar 30 '21 at 14:10
  • Does [extract column value based on another column pandas dataframe](https://stackoverflow.com/questions/36684013/extract-column-value-based-on-another-column-pandas-dataframe) answer your question? – wwii Mar 30 '21 at 14:15

1 Answers1

0
df3_merged[df3_merged['Country Name'] == country_name][year]
  • df3_merged['Country_Name'] == country_name return a boolean series which indicates each value in column Country Name is equal with country_name.
  • df3_merged[df3_merged['Country Name'] == country_name] is indexing with boolean series which filters out the False element.

If you want to use a function, you can use apply() which definitely complicates the problem:

def pop_bikers(country_name, year):
    def pop_bikers_helper(row, country_name, year):
        if (row['Country Name'] == country_name):
            return row[year]

    year_series = df3_merged.apply(pop_bikers_helper, args=(country_name, year), axis=1).dropna()

    if year_series.empty:
        return -1  # no matched 'Country Name' and 'year'
    else:
        return year_series.iloc[0]

pop_bikers(country_name, year)
Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52