【问题标题】:Python combine integer columns to create multiple columns with suffixPython组合整数列以创建带后缀的多个列
【发布时间】:2021-02-04 04:32:46
【问题描述】:

我有一个包含员工调查结果样本的数据框,如下所示。 delta 列中的值只是 FY21 和 FY20 列之间的差异。

Employee           leadership_fy21  leadership_fy20  leadership_delta   comms_fy21 comms_fy20 comms_delta
patrick.t@abc.com  88               50               38                 90         80         10
johnson.g@abc.com  22               82               -60                80         90         -10 
pamela.u@abc.com   41               94               -53                44         60         -16
yasmine.a@abc.com  90               66               24                 30         10         20

我想创建多个列 一世。包含 fy21 值中的 % ii.将其与带有 delta 后缀的列合并,使 delta 值在 () 中。

示例输出为:

Employee           leadership_fy21  leadership_delta  leadership_final comms_fy21 comms_delta comms_final
patrick.t@abc.com  88               38               88% (38)           90         10         90% (10)      
johnson.g@abc.com  22               -60              22% (-60)          80         -10        80% (-10)       
pamela.u@abc.com   41               -53              41% (-53)          44         -16        44% (-16)      
yasmine.a@abc.com  90               24               90% (24)           30         20         30% (20)    

我已经尝试了以下代码,但它似乎不起作用。这可能与 numpy 无法组合字符串有关。感谢我能得到的任何形式的帮助,谢谢。

#create a list of all the rating columns
ratingcollist = ['leadership','comms','wellbeing','teamwork']


#create a for loop to get all the columns that match the column list
for rat in ratingcollist:
    cols = df.filter(like=rat).columns
    fy21cols = df[cols].filter(like='_fy21').columns
    deltacols = df[cols].filter(like='_delta').columns

    if len(cols) > 0:
        df[f'{rat.lower()}final'] = (df[fy21cols].values.astype(str) + '%' + '(' + df[deltacols].values.astype(str) + ')')

【问题讨论】:

    标签: python pandas dataframe numpy for-loop


    【解决方案1】:

    你可以这样做:

    def yourfunction(ratingcol):
        x=df.filter(regex=f'{ratingcol}(_delta|_fy21)')
        fy=x.filter(regex='21').iloc[:,0].astype(str)
        delta=x.filter(regex='_delta').iloc[:,0].astype(str)
    
        return(fy+"%("+delta+")")
        
    yourfunction('leadership')
    
    0     88%(38)
    1    22%(-60)
    2    41%(-53)
    3     90%(24)
    

    然后,您可以使用 for 循环创建列

    for i in ratingcollist:
        df[f"{i}_final"]=yourfunction(i)
    

    【讨论】:

    • 嘿,它似乎无法工作,我收到 IndexError: single positional indexer is out-of-bounds
    • 每个评级栏都有 fy21 和 delta 吗?如果没有,这就是您收到此错误的原因
    • 哦,是的,你是对的,这是为列标题命名的情况。这行得通!
    猜你喜欢
    • 2020-02-01
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多