我有两栏熊猫,数据如下所示。
code fx category
AXD AXDG.R cat1
AXF AXDG_e.FE cat1
333 333.R cat1
....还有其他类别,但我只对cat1感兴趣。
我希望组合code列中的所有内容,以及fx列中.之后的所有内容,并将代码列替换为新的组合,而不影响其他行。
code fx category
AXD.R AXDG.R cat1
AXF.FE AXDG_e.FE cat1
333.R 333.R cat1
.....这是我的代码,我认为我必须使用regex,但我不知道如何以这种方式组合它。
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)我也不知道如何选择第二列。任何帮助都将不胜感激。
发布于 2021-12-19 17:59:50
还有其他的分类,但我只对cat1感兴趣
您可以使用str.split与series.where一起添加cat1的扩展:
df['code'] = (df['code'].astype(str).add("."+df['fx'].str.split(".").str[-1])
.where(df['category'].eq("cat1"),df['code']))print(df)
code fx category
0 AXD.R AXDG.R cat1
1 AXF.FE AXDG_e.FE cat1
2 333.R 333.R cat1发布于 2021-12-19 18:00:56
您可以extract fx的部分并将其附加到code
df['code'] += df['fx'].str.extract('(\..*$)')[0]产出:
code fx category
0 AXD.R AXDG.R cat1
1 AXF.FE AXDG_e.FE cat1
2 333.R 333.R cat1仅限于cat1:
df.loc[df['category'].eq('cat1'), 'code'] += df['fx'].str.extract('(\..*$)')[0]发布于 2021-12-19 18:01:02
您可以使用Series.str.extract
df['code'] = df['code'].astype(str) + np.where(df['category'].eq('cat1'), df['fx'].astype(str).str.extract('(\..+)')[0], '')输出:
>>> df
code fx category
0 AXD.R AXDG.R cat1
1 AXF.FE AXDG_e.FE cat1
2 333.R 333.R cat1https://stackoverflow.com/questions/70413959
复制相似问题