PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 5, 2022

[FIXED] How could I use this function inside pandas with lambda

 November 05, 2022     dataframe, lambda, pandas, python     No comments   

Issue

I have a problem. I have a dataframe, that contains ISO-codes of countries. I want to change these ISO-codes to country names. But unfortunately I do not know how I could use these functions inside a .apply(lambda x:) function.

Dataframe

   id country
0   1      DE
1   2      DE
2   3      CN
3   4      BG
4   3      CN
5   4      BG
6   5      BG

Code

import pandas as pd
import pycountry

input_countries = ['BG', 'CN', 'DE']

countries = {}
for country in pycountry.countries:
    countries[country.alpha_2] = country.name

codes = [countries.get(country, 'Unknown code') for country in input_countries]

import pandas as pd
d = {'id': [1, 2, 3, 4, 3, 4, 5], 'country': ['DE', 'DE', 'CN', 'BG', 'CN', 'BG', 'BG']}
df = pd.DataFrame(data=d)
# print(df)


df['country'] = df['country'].apply(lambda x: ...)

What I want

   id country
0   1      Germany
1   2      Germany
2   3      China
3   4      Bulgaria
4   3      China
5   4      Bulgaria
6   5      Bulgaria

Solution

I think you should use df.apply instead of df['country'].apply to create new function from the given value in country column

import pandas as pd
import pycountry

input_countries = ['BG', 'CN', 'DE']

countries = {}
for country in pycountry.countries:
    countries[country.alpha_2] = country.name

codes = [countries.get(country, 'Unknown code') for country in input_countries]

import pandas as pd
d = {'id': [1, 2, 3, 4, 3, 4, 5], 'country': ['DE', 'DE', 'CN', 'BG', 'CN', 'BG', 'BG']}
df = pd.DataFrame(data=d)
# print(df)


df['country'] = df.apply(lambda x: countries[x['country']], axis=1) 


Answered By - tax evader
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing