我有一个数据帧(df)
,其列名如下所示,我想将其重命名为任何特定的名称
重命名条件:
- 删除列名中的下划线
-
- 将
-
后面的第一个字母从小写替换为大写
原始列名
df.head(1)
risk_num start_date end_date
12 12-3-2022 25-3-2022
所需列名
df.头(1(
riskNum startDate endDate
12 12-3-2022 25-3-2022
这条蟒蛇怎么会这样。
使用Index.map
:
#https://stackoverflow.com/a/19053800/2901002
def to_camel_case(snake_str):
components = snake_str.split('_')
# We capitalize the first letter of each component except the first one
# with the 'title' method and join them together.
return components[0] + ''.join(x.title() for x in components[1:])
df.columns = df.columns.map(to_camel_case)
print (df)
riskNum startDate endDate
0 12 12-3-2022 25-3-2022
或者修改Panda的正则表达式解决方案:
#https://stackoverflow.com/a/47253475/2901002
df.columns = df.columns.str.replace(r'_([a-zA-Z0-9])', lambda m: m.group(1).upper(), regex=True)
print (df)
riskNum startDate endDate
0 12 12-3-2022 25-3-2022
使用str.replace
:
# Enhanced by @Ch3steR
df.columns = df.columns.str.replace('_(.)', lambda x: x.group(1).upper())
print(df)
# Output
# risk_num start_date end_date very_long_column_name
riskNum startDate endDate veryLongColumnName
0 12 12-3-2022 25-3-2022 0
以下代码将为您完成
df.columns = [x[:x.find('_')]+x[x.find('_')+1].upper()+x[x.find('_')+2:] for x in df.columns]