简体   繁体   中英

Mapping Values of key in Dictionary present in dataframe columns

I have a dataframe A with column 'col_1' and values of column is A and B and and I am trying to map the values of A and B present in Dictionary

DataFrame A:

enter image description here

and have dictionary

enter image description here

and I want the output like this

Dataframe:

col_1 Values

  1. A 1
  2. A 2
  3. A 3
  4. B 1
  5. B 2

Any help will be highly appreciated thanks

I tried to frame your problem properly:

df = pd.DataFrame({"col_1":["A","A","A","B","B"]})

Printing df gives us your dataframe shown in the image above:

print(df)

    col_1
0     A
1     A
2     A
3     B
4     B

Here is your dictionary:

dict1 = {"A":[1,2,3], "B":[1,2]}

I created an empty list to hold the elements then stack up the list with your request, and finally created a new column called values and write the list into the column

values1 = []

for key,value_list in dict1.items():
    for item in value_list:
        value_item = key+" "+ str(item)
        values1.append(value_item)

df["values"] = values1 

printing df results into:

df


     col_1  values
0     A      A 1
1     A      A 2
2     A      A 3
3     B      B 1
4     B      B 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM