如何在Python中结合字典键值生成指定格式的债券名称字符串?
Got it, let's fix this formatting task step by step. You already started on the right track with splitting the names—now we just need to map the split parts to your dictionaries and stitch everything together.
First, let's recap your existing data for clarity:
import pandas as pd time = {'JAN':'A','FEB':'B','MAR':'C','APR':'D','MAY':'E','JUN':'F','JUL':'H'} currency={'USD':'US','EUR':'EU','GBP':'GB','HUF':'HF'} bond_names=pd.DataFrame({'Names':['Bond.USD.JAN.21','Bond.USD.MAR.25','Bond.EUR.APR.22','Bond.HUF.JUN.21','Bond.HUF.JUL.23','Bond.GBP.JAN.21']})
The Core Fix
When you split a bond name like Bond.USD.JAN.21 with split('.'), you get a list: ['Bond', 'USD', 'JAN', '21']. We just need to pull the relevant elements from this list, look them up in your dictionaries, and concatenate the results.
Here's the one-liner to add the formatted column:
bond_names['Formatted_Names'] = bond_names['Names'].apply( lambda x: f"{currency[x.split('.')[1]]}{time[x.split('.')[2]]}{x.split('.')[3]}" )
Breakdown of the Lambda Function
x.split('.')[1]: Grabs the currency code (e.g.,USDfrom the split list)currency[x.split('.')[1]]: Maps the currency code to its 2-letter abbreviation (e.g.,USD→US)x.split('.')[2]: Grabs the month code (e.g.,JAN)time[x.split('.')[2]]: Maps the month code to its single letter (e.g.,JAN→A)x.split('.')[3]: Grabs the last two digits of the year (e.g.,21)- The f-string glues all three parts together into your desired format (e.g.,
US + A + 21→USA21)
Result
If you print the updated DataFrame with print(bond_names), you'll get:
Names Formatted_Names 0 Bond.USD.JAN.21 USA21 1 Bond.USD.MAR.25 USC25 2 Bond.EUR.APR.22 EUD22 3 Bond.HUF.JUN.21 HFF21 4 Bond.HUF.JUL.23 HFH23 5 Bond.GBP.JAN.21 GBA21
Bonus: Make It Robust
If there's a chance your bond names might have currency/month codes not in your dictionaries, use dict.get() to avoid KeyError (replace missing values with a placeholder like XX/X):
bond_names['Formatted_Names'] = bond_names['Names'].apply( lambda x: f"{currency.get(x.split('.')[1], 'XX')}{time.get(x.split('.')[2], 'X')}{x.split('.')[3]}" )
内容的提问来源于stack exchange,提问作者VSP

