Home > other >  How to get first element of a list inside dictionary and add to Pandas Dataframe column in Python?
How to get first element of a list inside dictionary and add to Pandas Dataframe column in Python?

Time:06-06

I have a dictionary like this:

dict = {"key 1": ["val 1", "val 2"],
        "key 2": ["val 3", "val 4", "val 5"],
        "key 3": ["val 6", "val 7"],
         ...
}

I also have a pandas dataframe that contains all the keys like this:

     key
0    key 1
1    key 2
2    key 3
...

I need to add a new column to the dataframe called first_key that takes the first element of the list inside the dictionary for each key in the dict, so it ends up like this:

     key      first_key
0    key 1    val 1
1    key 2    val 3
2    key 3    val 6
...

which I have had some trouble with... doing something like this doesn't work:

df['first_key'] = df['key'].map(dict[WHAT HERE][0])

:D

CodePudding user response:

Try:

dct = {
    "key 1": ["val 1", "val 2"],
    "key 2": ["val 3", "val 4", "val 5"],
    "key 3": ["val 6", "val 7"],
}

df["first_key"] = df["key"].apply(dct.get).str[0]
print(df)

Prints:

     key first_key
0  key 1     val 1
1  key 2     val 3
2  key 3     val 6

Or:

df["first_key"] = df["key"].map(dct).str[0]

CodePudding user response:

Try this:

new_dict = {k: v[0] for k, v in your_dict.items()}

df['first_key'] = df['key'].map(new_dict)

CodePudding user response:

Use map and .str[0]:

df['first_key'] = df['key'].map(dict).str[0]

Output:

>>> df
     key first_key
0  key 1     val 1
1  key 2     val 3
2  key 3     val 6
  • Related