如何在Python中用连接函数替换函数

x33g5p2x  于 2023-06-07  发布在  Python
关注(0)|答案(2)|浏览(116)

我在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 Notebook中使用Pandas获得预期的输出?
我是Python编程新手。

cygmwpex

cygmwpex1#

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
a2mppw5e

a2mppw5e2#

尝试:

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

相关问题