You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python拆分列表文本时保留完整实体并转为pandas DataFrame

解决思路

核心逻辑

只有净资产占比为「数字+小数点+数字」的固定格式,证券名称、分类字段均为不含数字的文本,因此通过正则表达式成对提取「名称文本」和「数值」,就能避免拆分带空格的完整企业名称。

实现代码

import re
import pandas as pd

# 你修正后的原始数据列表
corrected_text = ['Security Name % to Net Assets* DEBENtURES 0.04 Britannia Industries Ltd. EQUity & RELAtED 96.83 HDFC Bank 6.98 ICICI 4.82 Infosys 4.37 Reliance 4.05 Bajaj Finance 3.82 Housing Development Corpn. 3.23 Grindwell Norton 3.22 SRF Sun Pharmaceutical 2.85 Bharti Airtel 2.82 DLF 2.64 Ultratech Cement 2.62 SKF India 2.45 Crompton Greaves Consumer Electricals 2.42 Avenue Supermarts 2.41 Axis ABB 2.35 Titan Co. 2.29 Kotak Mahindra 2.09 Cipla 2.05 Laurus Labs 2.04 Wipro 1.77 Happiest Minds Technologies 1.68 Canara 1.67 Shree 1.63 1.59 Pidilite 1.50 Lombard General Insurance 1.48 Cholamandalam Investment 1.45 Tech 1.35 State of 1.31 Hindustan Unilever 1.30 Vardhman Textiles Larsen Toubro 1.24 Dabur 1.22 Neogen Chemicals 1.10 Eicher Motors 1.09 Thermax 1.08 TATA Consultancy Services 1.05 Indian Railway Catering Tourism 0.98 Firstsource Solutions 0.97 Nestle 0.86 Asian Paints 0.84 Welspun 0.72 IndusInd 0.63 SBI Life 0.50 Deepak Nitrite 0.46 Adani Ports and Special Economic Zone 0.36 Gateway Distriparks 0.33 Bharat Forge 0.22 tREPS on G-Sec or t-Bills 2.81 Cash Receivables 0.32 tOtAL']

# 1. 清洗空白字符,统一为单个空格
raw_str = re.sub(r'\s+', ' ', corrected_text[0]).strip()

# 2. 正则匹配:分组捕获【名称】和【对应数值】
pattern = r'([^\d.]+?)\s*(\d+\.\d+)'
matches = re.findall(pattern, raw_str)

# 3. 清洗匹配结果,可按需过滤表头
result = []
for name, val in matches:
    clean_name = name.strip()
    # 如需保留DEBENtURES、权益类等分类统计项,删除下方的过滤判断即可
    if 'Security Name' not in clean_name and clean_name:
        result.append([clean_name, float(val)])

# 4. 转成pandas DataFrame
df = pd.DataFrame(result, columns=['证券名称', '净资产占比(%)'])
print(df)

效果说明

运行后会得到结构完整的DataFrame,企业名称不会被拆分,数值和名称一一对应,完全符合你要求的输出结构。

注意事项

  • 你提供的修正后文本中部分证券名称后缺失了对应数值(比如SRF后缺3.22),建议提前补全原始文本避免匹配遗漏
  • 如果后续遇到名称中带数字的证券,调整正则的匹配规则即可适配

内容的提问来源于stack exchange,提问作者technophile_3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 17:06:05