python - 在熊猫中动态替换所有列的最后一个字符
问题描述
我有一个列名以整数结尾的数据框。我需要将整数部分替换为从特定月份开始到持续 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
你能帮帮我吗?
解决方案
# 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"]
推荐阅读
- java - NullPointerException @Autowired 服务。JAX-RS + SpringBoot + WildFly
- php - 将通过 URL 传递的值插入到生成的表单中
- python - 有没有办法在 django 中使用 Python 中开发的查询
- sql - Oracle SQL - 多个 JOINS 性能问题
- python - AttributeError:“模块”对象没有属性“转储”
- python - 在 vscode jupyter notebook 输出中显示问题/输入
- mule4 - Mule 4:数据库:如何在数据库“查询文本”中将 SQL 查询作为变量传递?
- python - 连接numpy数组切片的最快方法
- c++ - 是否可以使用 nlohmann/json 序列化嵌套/复杂类?
- java - 初始化后如何向 JFrame 添加组件?