首页 > 解决方案 > 在熊猫中动态替换所有列的最后一个字符

问题描述

我有一个列名以整数结尾的数据框。我需要将整数部分替换为从特定月份开始到持续 12 个月的月份和年份。如何以动态方式进行。示例可能是:

columns = ['A_0','A_1','A_2','A_3','B_0','B_1','B_2', 'B_3'])

我想实现:

['A_OCT20','A_SEP20','A_AUG20','A_JUL20','B_OCT20','B_SEP20','B_AUG20','B_JUL20']

我正在尝试这个

base_mon = "OCT20"

for i in range(4):
    curr_mon = pd.to_datetime('01'+base_mon, format='%d%b%y') - relativedelta(months=i)
    curr_mon_str2 = curr_mon.strftime('%b%y').upper()
    
    df.columns = df.columns.str.replace(str(i), curr_mon_str2)

但我的输出看起来像这样

 A_OCTAUG200  A_SEPAUG200  A_AUG20  A_JUL20  B_OCTAUG200  B_SEPAUG200 B_AUG20  B_JUL20

你能帮帮我吗?

标签: pythonpandas

解决方案


# forming a base date for calculations
base_mon = "OCT20"
base_date = pd.to_datetime(base_mon, format="%b%y")

# to-be filled
new_columns = []

# for each column name...
for col in df.columns:
    # split into 3 parts: characters, underscore and digits
    name, _, digit = col.partition("_")

    # get the offseted month & year
    date = base - pd.DateOffset(months=int(digit))
    
    # add back the name (e.g., `"A"`), underscore and the new date
    new_col = name + "_" + date.strftime("%b%y").upper()

    # store in a list
    new_columns.append(new_col)

# change the original columns
df.columns = new_columns
>>> new_columns
["A_OCT20", "A_SEP20", "A_AUG20", "A_JUL20", "B_OCT20", "B_SEP20", "B_AUG20", "B_JUL20"]

推荐阅读