0

I have a Pandas data frame with several columns including date, address, value, and type. I also have a dictionary with key: value pairs as address: alias. I want to create a new database which will have columns: date, address, value, type, alias in such a way that the alias value is assigned to the cell in column address with a matching key. How can I do it in an easy way?

An example: DataFrame

| date    | address | value | type |
| 01-01-23| n167867 | 10    | A    |
| 03-02-23| b2567gh | 30    | A    |
| 03-03-23| a78956b | 4     | B    |
| 12-05-23| n1hd789 | 25    | C    |

dictionary:

{n167867 : ABC, 
b2567gh : XYZ, 
a78956b : CGH,
n1hd789 : ZET}

new data frame:

| date    | address | value | type | alias |
| 01-01-23| n167867 | 10    | A    | ABC   |
| 03-02-23| b2567gh | 30    | A    | XYZ   |
| 03-03-23| a78956b | 4     | B    | CGH   |
| 12-05-23| n1hd789 | 25    | C    | ZET   |
Ziva
  • 3,181
  • 15
  • 48
  • 80

2 Answers2

1

You could use mapping

df['alias'] = df['address'].map({'n167867' : 'ABC', 'b2567gh' : 'XYZ', 'a78956b' : 'CGH', 'n1hd789' : 'ZET'})

       date  address  value type alias
0  01-01-23  n167867     10    A   ABC
1  03-02-23  b2567gh     30    A   XYZ
2  03-03-23  a78956b      4    B   CGH
3  12-05-23  n1hd789     25    C   ZET
amance
  • 883
  • 4
  • 14
1

You could create a dataframe from the dictionary and then merge the two dataframes:

data_dict = {
"n167867" : "ABC", 
"b2567gh" : "XYZ", 
"a78956b" : "CGH",
"n1hd789" : "ZET"
}
additional_data = pd.DataFrame.from_dict(
    data_dict,
    orient="index",
    columns=["alias"])

df = pd.merge(original_df, additional_data, left_on="address", right_index=True)
ini
  • 175
  • 9