python - pandas 中的高级字符串编辑

标签 python pandas

我正在使用一个数据集,其中公司名称与我想要合并的数据集不太匹配。

作为解决方案的一部分,我想在数据框中的一列中编辑公司名称。假设我有一个公司名称列表,我想做的是:

diff = ['some list of tickers']
for security in df.query("tic in @diff").security.unique():
    result = re.search(expression, security)[0].upper()
    result = result.replace('CORPORATION', 'CORP')
    result = result.replace('COMPANY', 'CO')
    result = result.replace('OF','')
    result = result.replace('F', '')
    result = result.strip()

我认为甚至可能有一个优雅的解决方案,我可以运行自定义函数来修改单元格的值,但我对 pandas 还不够熟悉,还不知道如何做到这一点。

我正在像这样编辑的数据框。

          caldt      tic              security             curshrt
2672    1988-06-01  ITSCW   Industrial Training Systems,    0
8007    1988-07-01  ITSCW   Industrial Training Systems,    0
44772   1989-03-01  MMNT    Momentum, Inc.  0
49865   1989-04-01  MMNT    Momentum, Inc.  372
54925   1989-05-01  MMNT    Momentum, Inc.  78
... ... ... ... ...
1077214 2007-06-01  ABBI    Abraxis BioScience, Inc. - Common stock 4486255
1080530 2007-07-01  ABBI    Abraxis BioScience, Inc. - Common stock 4659919
1083835 2007-08-01  ABBI    Abraxis BioScience, Inc. - Common stock 4265095
1087148 2007-09-01  ABBI    Abraxis BioScience, Inc. - Common stock 4018741
1090424 2007-10-01  ABBI    Abraxis BioScience, Inc. - Common stock 4064510

我正在去掉标点符号并更改一些缩写和单词

最佳答案

我认为您的代码可能会修改如下:

import re

diff = ['some list of tickers']
d = dict([('CORPORATION', 'CORP'), ('COMPANY', 'CO'), ('OF',''), ('F', '')])
s = df.loc[df.tic.isin(diff), 'security']
df.loc[df.tic.isin(diff), 'security'] = (s.str.findall(expression, flags=re.I).str[0].
                                           str.upper().replace(d))

注意:表达式是您的搜索模式。

关于python - pandas 中的高级字符串编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58869776/

相关文章:

python - __setattr__ 在此 python 代码中做了什么?

python - 如何展平 pandas DataFrame 中的分层列索引?

python - str.split() 返回的 Pandas 排序列表

Python 测试 - 重置所有模拟?

python - 通过内部设置的列去除重复的行

python - 如何在Python中获取ROS MSG长度?

Python-如何从文件中删除列

python - 聚合行 Pandas

python - 通过查看第一列来堆叠一对列

python-3.x - 如何标准化滚动 Pandas 数据框的子集?