'Python Dataframe column matching
I have 2 columns A & B. A contains text values separated by '_' and B has some description related to A.
Example:
*Col Terms
AB_BCN_PRC About Bitcoin Price
AC_CR_STT Account credit Statement
A6_AT_MD Audi Automatic Model*
I need to map A and B so in future if a new value comes in A it should frame B automatically
Example:
*A B
AB_CR_STT About credit Statement*
Any idea or possible ways to get this done?
Solution 1:[1]
If you can define a good complete mapping dictionary (each name separated by _ as a key, the text represented by this name as a value), it can be easily implemented, and finally I used pandas to combine into the format in your example, you can also use print directly, the main focus on the function gen_terms, by the name you provide to return the full text, you can expand on this basis according to the functions you need(Make sure that each item in the name you pass in, separated by _, is the one you defined in the col_map)?
import pandas as pd
def gen_terms(col):
col_map = {
"AB": "About",
"BCN": "Bitcoin",
"PRC": "Price",
"AC": "Account",
"CR": "credit",
"STT": "Statement",
"A6": "Audi",
"AT": "Automatic",
"MD": "Model",
}
spans = col.split("_")
return " ".join([col_map.get(data) for data in spans])
name = "AB_CR_STT"
df = pd.DataFrame({"A": ["AB_CR_STT"], "B": [gen_terms("AB_CR_STT")]})
print(df)
# A B
# 0 AB_CR_STT About credit Statement
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | maya |
