Extract element from pandas list-series and store as separate series

Viewed 128

I have this df (with sample desired result)

dfn = pd.DataFrame({"country_code": ["USA, UK, FRA", "RUS, ZHC, JAP", "IN, BRA, ES"], 
                    "all_but_american_desired": [["United Kingdom", "France"], ["Russia", "China", "Japan"], ["India", "Spain"]]})

where I "translate" the (so far) strings into new meanings and store as a list of elements

masked = {"USA":"United States", "UK":"United Kingdom", "FRA":"France", 
          "RUS":"Russia", "ZHC":"China", "JAP":"Japan", 
          "IN":"India", "BRA":"Brazil", "ES":"Spain"}

dfn["country_name"] = dfn["country_code"].apply(lambda x: [", ".join({masked[i] for i in x.split(", ")})])

I would then want to extract some of the translated country_name series going by an external list, americanand place them on a separate series (all_but_american)

american = ["United States", "Brazil"]

Result should be same as the all_but_american_desired series. What I've tried so far:

dfn["all_but_american1"] = dfn["country_name"].apply(lambda x: [i for i in x if i not in american])

I've used the attempt1 very same approach previously and it's worked, but this time nothin's working and I can't find the reason for it (I've also tried other approaches this time, but as I'm not familiar with them I'll refrain from posting)... Can someone check it please? If possible with an explanation as to what I'm doing wrong too.

1 Answers

For country_name create lists instead one element list with joined values:

dfn["country_name"] = dfn["country_code"].apply(lambda x: [masked[i] for i in x.split(", ")])

And then your second solution working well:

american = ["United States", "Brazil"]

dfn["all_but_american1"] = dfn["country_name"].apply(lambda x: [i for i in x if i not in american])
print (dfn)
    country_code  all_but_american_desired  \
0   USA, UK, FRA  [United Kingdom, France]   
1  RUS, ZHC, JAP    [Russia, China, Japan]   
2    IN, BRA, ES            [India, Spain]   

                              country_name         all_but_american1  
0  [United States, United Kingdom, France]  [United Kingdom, France]  
1                   [Russia, China, Japan]    [Russia, China, Japan]  
2                   [India, Brazil, Spain]            [India, Spain]  
Related