将 pandas 中的 2 个字符串列与两列中的不同条件组合起来

ana*_*chy 6 python dataframe pandas

我在 pandas 中有两列,数据如下所示。

code fx         category
AXD  AXDG.R     cat1
AXF  AXDG_e.FE  cat1 
333  333.R      cat1
....
Run Code Online (Sandbox Code Playgroud)

还有其他类别,但我只对 cat1 感兴趣。

我想组合该code列中的所有内容以及该.列中的所有内容fx,并用新的组合替换代码列,而不影响其他行。

code    fx         category
AXD.R   AXDG.R     cat1
AXF.FE  AXDG_e.FE  cat1
333.R   333.R      cat1
.....
Run Code Online (Sandbox Code Playgroud)

这是我的代码,我想我必须使用正则表达式,但我不确定如何以这种方式组合它。

df.loc[df['category']== 'cat1', 'code'] = df[df['category'] == 'cat1']['code'].str.replace(r'[a-z](?=\.)', '', regex=True).str.replace(r'_?(?=\.)','', regex=True).str.replace(r'G(?=\.)', '', regex=True)
Run Code Online (Sandbox Code Playgroud)

我也不知道如何选择第二列。任何帮助将不胜感激。

ank*_*_91 3

还有其他类别,但我只对 cat1 感兴趣

您可以使用str.splitwithseries.where来添加 cat1 的扩展名:

df['code'] = (df['code'].astype(str).add("."+df['fx'].str.split(".").str[-1])
             .where(df['category'].eq("cat1"),df['code']))
Run Code Online (Sandbox Code Playgroud)
print(df)

     code         fx category
0   AXD.R     AXDG.R     cat1
1  AXF.FE  AXDG_e.FE     cat1
2   333.R      333.R     cat1
Run Code Online (Sandbox Code Playgroud)

  • 是的,我实际上想通了,哈哈,添加了 as 类型,它起作用了..谢谢! (2认同)