我有(df)如下所示列名的資料框,我想將其重命名為任何特定名稱
重命名條件:
- 去掉
-列名中的下劃線 -將from smallcase之后的第一個字母替換為大寫。
原始列名
df.head(1)
risk_num start_date end_date
12 12-3-2022 25-3-2022
預期的列名
df.head(1)
riskNum startDate endDate
12 12-3-2022 25-3-2022
這怎么能在python中完成。
uj5u.com熱心網友回復:
使用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
uj5u.com熱心網友回復:
使用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
或修改熊貓的正則運算式解決方案:
#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
uj5u.com熱心網友回復:
以下代碼將為您做到這一點
df.columns = [x[:x.find('_')] x[x.find('_') 1].upper() x[x.find('_') 2:] for x in df.columns]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/447960.html
標籤:Python python-3.x 熊猫 数据框
