【问题标题】:Rename column names of my data frame in Pandas在 Pandas 中重命名我的数据框的列名
【发布时间】:2021-09-03 19:54:51
【问题描述】:

在我的数据框中,有 500 列的模式类似于

GroupNoIDFirstNameLastName (例如:列名=Gr1234AdamSmith,Gr2567DavidBlake.......)

其中 Gr1, Gr2 = GroupNo; 234, 567 = 身份证;亚当史密斯,大卫布莱克 = FirstNameLastName

我想重命名所有 500 列以仅显示他们的名字和姓氏。

类似于 亚当·史密斯、大卫·布莱克

我怎样才能做到这一点?

非常感谢您的帮助。

【问题讨论】:

  • 您的问题在这里得到解答了吗?

标签: pandas rename


【解决方案1】:

首先通过列表切片[6:] 剥离组,然后从How to do CamelCase split in python,您可以拆分名字和姓氏,然后用户' '.join() 得到您想要的:

import re
def camel_case_split(identifier):
    matches = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', identifier)
    return [m.group(0) for m in matches]

#rename (reassign)
df.columns = df.columns.map(lambda x: ' '.join(camel_case_split(x[6:])))

【讨论】:

    【解决方案2】:

    可以使用 Pandas 的重命名方法

    import re
    
    def get_first_last(string):
        # 1. Get the last item of split on number of group and ID with regex -> ['Gr', 'AdamSmith']
        fullname = re.split(r'[0-9]+', string)[-1]
        # 2. Match the consecutive camelCase characters and add space between them
        first_last = re.sub(r'([a-z])([A-Z])', '\g<1> \g<2>', fullname)
        return first_last
       
    # Get first and lastname for each column in dataframe and rename columns inplace
    df.rename(columns={c: get_first_last(c) for c in df.columns}, inplace=True)
    

    【讨论】:

      猜你喜欢
      • 2014-10-26
      • 2012-08-25
      • 2019-09-26
      • 2022-06-14
      • 2019-03-03
      • 2020-02-02
      • 2013-09-04
      • 1970-01-01
      • 2017-12-31
      相关资源
      最近更新 更多