1

I have a dataframe df_a, with a numpy-array named 'Language'. I want to create another numpy-array, LanguageCode, based upon Language and the Language codes associated with a Language.

df_a = pd.DataFrame({'Language':[['cantonese', 'japanese', 
                 'mandarin','american'],['mandarin','english'], 
                 ['american', 'mandarin','cantonese']]})```

df_a

     Language                                  LangugeCode
0   [cantonese, japanese, mandarin, american]  [zh_yue,ja,cmn,us]
1   [mandarin, english]                        [cmn,en]
2   [american, mandarin, cantonese]            [us,cmn,zh_yue'
2
  • The LanguageCode column is available in your df_a? Commented Oct 5, 2020 at 23:54
  • Where do you retrieve the language code? Using pycountry like this answer? Commented Oct 6, 2020 at 0:20

1 Answer 1

1

I assumed that you have a dictionary to associate language and language code, and then used map.

Please, check if it helps you:

Assumptions:

import pandas as pd
import numpy as np

df_a = pd.DataFrame({'Language':[['cantonese', 'japanese', 
                 'mandarin','american'],['mandarin','english'], 
                 ['american', 'mandarin','cantonese']]})

#this is the hypothetical dictionary
lang_codes = {'cantonese': 'zh_yue','japanese': 'ja', 'mandarin': 'cmn','american': 'us','english': 'en'}

What you can do:

df_a['Language Code'] = [list(map(lambda x: lang_codes[x], row)) for row in df_a.Language]

Checking:

#getting the numpy array format
language_code = np.array(df_a['Language Code'])

type(language_code)

numpy.ndarray

And your dataframe will be:

    Language                                    Language Code
0   [cantonese, japanese, mandarin, american]   [zh_yue, ja, cmn, us]
1   [mandarin, english]                         [cmn, en]
2   [american, mandarin, cantonese]             [us, cmn, zh_yue]
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I have a list of matching code. I will try this. Thank you very much.
@JeffMagouirk, if this answer addresses your problem, please mark answer as accepted so community can read as a trusted solution. Thanks

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.