我需要帮助来找出一个解决方案,取代函数与一个连接函数在python

j2qf4p5b  于 2023-03-31  发布在  Python
关注(0)|答案(2)|浏览(109)

我在Excel文件中有一个阶段的列标题,另一列是AI80010_6,如下所示:

Stages       Ai80010_6
1          Ai80010_6.cardop.S1
2          Ai80010_6.cardop.XX
2          Ai80010_6.cardop.S2
2          Ai80010_6.fstmor.XX
2          A120300_5.cardop.S2
2          A120300_5.cardop.XX

预期结果如下:

Stages       Ai80010_6                  output
     1          Ai80010_6.cardop.S1         Ai80010_6.cardop.S1
     2          Ai80010_6.cardop.XX         Ai80010_6.cardop.S2 
     2          Ai80010_6.cardop.S2         Ai80010_6.cardop.S2
     2          Ai80010_6.fstmor.XX         Ai80010_6.fstmor.S2
     2          A120300_5.cardop.S2         A120300_5.cardop.S2
     2          A120300_5.cardop.XX         A120300_5.cardop.S2

你能帮我得到预期的输出在jupyter笔记本与Pandas
我是新的python编码,所以这将是伟大的,如果你能帮助我与这种情况

jyztefdp

jyztefdp1#

rsplit,将mask与载物台一起使用并再次合并:

tmp = df['Ai80010_6'].str.rsplit('.', n=1, expand=True)

df['output'] = tmp[0]+'.'+tmp[1].mask(tmp[1].eq('XX'),
                                      'S'+df['Stages'].astype(str))

或者,只需覆盖舞台:

df['output'] = (df['Ai80010_6'].str.extract(r'(.*\.)[^.]*$', expand=False)
                +'S'+df['Stages'].astype(str)
                )

输出:

Stages            Ai80010_6               output
0       1  Ai80010_6.cardop.S1  Ai80010_6.cardop.S1
1       2  Ai80010_6.cardop.XX  Ai80010_6.cardop.S1
2       2  Ai80010_6.cardop.S2  Ai80010_6.cardop.S2
3       2  Ai80010_6.fstmor.XX  Ai80010_6.fstmor.S2
4       2  A120300_5.cardop.S2  A120300_5.cardop.S2
5       2  A120300_5.cardop.XX  A120300_5.cardop.S2
djmepvbi

djmepvbi2#

试试看:

df['output'] = df.apply(lambda x: x['Ai80010_6'].replace('XX', f'S{x["Stages"]}') , axis=1)
print(df)

图纸:

Stages            Ai80010_6               output
0       1  Ai80010_6.cardop.S1  Ai80010_6.cardop.S1
1       2  Ai80010_6.cardop.XX  Ai80010_6.cardop.S2
2       2  Ai80010_6.cardop.S2  Ai80010_6.cardop.S2
3       2  Ai80010_6.fstmor.XX  Ai80010_6.fstmor.S2
4       2  A120300_5.cardop.S2  A120300_5.cardop.S2
5       2  A120300_5.cardop.XX  A120300_5.cardop.S2

相关问题