从pandas数据框列获取括号内的文本,并将输出复制到同一列中

问题描述 投票:1回答:1

我只想获取括号内的文本,并将此文本保留在同一列中。

我具有以下数据框df:

id     feature
1      mutation(MI:0118)
2      mutation(MI:0119)
3      mutation(MI:01120)

预期输出是:

id     feature
1      MI:0118
2      MI:0119
3      MI:01120

我尝试了以下正则表达式,但不允许我将其复制到同一列。

df['feature'] = df['feature'].str.extract(r"\((.*?)\)", expand=False)

我收到以下警告,并且上面的代码将功能列中的所有值都转换为NaN

/home/lib/python2.7/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  """Entry point for launching an IPython kernel.

谢谢

python regex
1个回答
0
投票

尝试使用下面的代码使用不同的模式:

df['feature'] = df['feature'].str.extract('.*\((.*)\).*', expand=False)
print(df)

输出:

   id   feature
0   1   MI:0118
1   2   MI:0119
2   3  MI:01120
© www.soinside.com 2019 - 2024. All rights reserved.