49795

How to replace dataframe column values with dictionary keys?

Question:

Suppose I have a dictionary:

dict = {"1" : "A", "2" : "B" , "3" : "C"}

and a data frame

df = pd.DataFrame() df["ID"] = pd.Series(["A","B","C"]) df["Desc"] = pd.Series(["Fruits","Vegs","Meat"])

The dataframe will look like this:

<a href="https://i.stack.imgur.com/0ih2x.png" rel="nofollow"><img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/0ih2x.png" data-original="https://i.stack.imgur.com/0ih2x.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" /></a>

How would I replace values in column df["ID"] with dictionary keys so that I have 1,2,3 in df["ID"] instead of A,B,C?

Answer1:

First create a reverse mapping:

In [363]: dict2 = {v : k for k, v in dict_.items()}

The assumption made here is that your values are unique. Now you can use pd.Series.replace:

In [367]: df.ID = df.ID.replace(dict2); df Out[367]: ID Desc 0 1 Fruits 1 2 Vegs 2 3 Meat <hr />

Alternative solution with pd.Series.map:

In [380]: df.ID = df.ID.map(dict2); df Out[380]: ID Desc 0 1 Fruits 1 2 Vegs 2 3 Meat

Also, I recommend you use a different name than dict, because there's already a builtin with that name.

Answer2:

Or you can just base on pandas .

df.ID=df.ID.map((pd.DataFrame(data=d,index=['Value',]).T.reset_index().set_index('Value'))['index']) Out[23]: ID Desc 0 1 Fruits 1 2 Vegs 2 3 Meat

Answer3:

Another way to do this would be:

dict1 = pd.DataFrame(dict.items()) dict1.columns = ['ID_1',"ID"] merge = pd.merge(df,dict1) del merge['ID'] merge = merge.rename(columns={'ID_1': 'ID'}) Desc ID 0 Fruits 1 1 Vegs 2 2 Meat 3

Recommend

  • PHP > Form a multi-dimensional array from a nested set model flat array
  • Sort NSDates inside NSDictionary inside NSArray?
  • REGEX to extract multiple name/value tokens (vbscript)
  • Dynamically calling nested functions based on arguments
  • Run-time Error 424 Object Required UserForm doesnt exist
  • Getting access to already created Chart.js chart
  • Truncate dictionary list values
  • Creating Array of Dictionary in Swift
  • Reading from Windows registry in Perl [duplicate]
  • How to exclude files in a custom clean task?
  • Send multimedia commands
  • Detect language of Word document
  • What is the equivalent of Android permissions in iOS development? [duplicate]
  • Loop through each key and value of php multidimensional array
  • Many to Many in Linq using Dapper
  • Are there any side effects from calling SQLAlchemy flush() within code?
  • netsh acl setting (need alternative method - registry settings?)
  • R convert summary result (statistics with all dataframe columns) into dataframe
  • SAXReader not re-ecape characters
  • Do I need to seed any random number generator before using EVP_PKEY_keygen of OpenSSL?
  • Make new pandas columns based on pipe-delimited column with possible repeats
  • Array with custom indexes in Ionic2
  • xtable package: Skipping some rows in the output
  • Groovy: Unexpected token “:”
  • Replace value with Factor in r data.table
  • Checking free space on FTP server
  • How to delay loading a property with linq to sql external mapping?
  • How to access EntityManager inside Entity class in EJB3
  • Repeat a vertical line on every page in Report Builder / SSRS
  • Jenkins: How To Build multiple projects from a TFS repository?
  • Check if a string to interpolate provides expected placeholders
  • Javascript + PHP Encryption with pidCrypt
  • Convert array of 8 bytes to signed long in C++
  • R: gsub and capture
  • AT Commands to Send SMS not working in Windows 8.1
  • VB.net deserialize, JSON Conversion from type 'Dictionary(Of String,Object)' to type '
  • Trying to get generic when generic is not available
  • Understanding cpu registers
  • Recursive/Hierarchical Query Using Postgres
  • Running Map reduces the dimensions of the matrices