Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas - add new column to dataframe from dictionary [duplicate]

Tags:

python

pandas

I would like to add a column 'D' to a dataframe like this:

U,L 111,en 112,en 112,es 113,es 113,ja 113,zh 114,es 

based on the following Dictionary:

d = {112: 'en', 113: 'es', 114: 'es', 111: 'en'} 

so that the resulting dataframe appears as:

U,L,D 111,en,en 112,en,en 112,es,en 113,es,es 113,ja,es 113,zh,es 114,es,es 

So far I tried the pd.join() method but I can't figured out how it works with Dictionaries.

like image 343
Fabio Lamanna Avatar asked Apr 22 '15 10:04

Fabio Lamanna


People also ask

How do I add a column to a pandas DataFrame?

In pandas you can add/append a new column to the existing DataFrame using DataFrame. insert() method, this method updates the existing DataFrame with a new column. DataFrame. assign() is also used to insert a new column however, this method returns a new Dataframe after adding a new column.

How do you turn a dictionary into a data frame?

You can convert a dictionary to Pandas Dataframe using df = pd. DataFrame. from_dict(my_dict) statement.


1 Answers

Call map and pass the dict, this will perform a lookup and return the associated value for that key:

In [248]:  d = {112: 'en', 113: 'es', 114: 'es', 111: 'en'} df['D'] = df['U'].map(d) df Out[248]:      U   L   D 0  111  en  en 1  112  en  en 2  112  es  en 3  113  es  es 4  113  ja  es 5  113  zh  es 6  114  es  es 
like image 66
EdChum Avatar answered Sep 18 '22 06:09

EdChum