首页 > 解决方案 > 如何从新闻摘要中提取股票代码 NUMBER?

问题描述

我有一个 Pandas 表,需要从存储在列中的文本中提取股票代码“00981”、“00823”。代码采用 (00000) 格式。该代码将位于文本摘要中的不同位置。请指教。

News
1 example(00981)example example example。 
2 example example example (00823)text text text 

所需的输出:

Code column
981
823

s = TABLE['News'].str.find('(')
e = s + 5
c = TABLE['News'].str[s:e]
TABLE["Code"] = c

标签: pythonstringpandas

解决方案


这对我有用:

print(df)
           News
0          1 example(00981)example example example。 
1      2 example example example (00823)text text...
-
df['stock_num'] = df['News'].str.extract('(\d{5})').astype(int)
print(df)
                                                    News stock_num
0          1 example(00981)example example example。      981
1      2 example example example (00823)text text...     823

要将字符串更改为数字,您可以利用该.astype()方法或pd.to_numeric(df['stock_number'])


推荐阅读