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

如何在Python中统计字符串内的财务契约数量

问题:统计金融契约列的契约数量

我有一份3000行的数据集,其中包含名为financial_covenants的字符串列,示例数据如下:

#financial_covenants
1Max. Debt to Cash Flow: Value is 6.00
2Max. Debt to Cash Flow: Decreasing from 4.00 to 3.00, Min. Fixed Charge Coverage Ratio: Value is 1.20
3Min. Interest Coverage Ratio: Value is 3.00
4Max. Debt to Cash Flow: Decreasing from 4.00 to 3.50, Min. Interest Coverage Ratio: Value is 3.00
5Max. Leverage Ratio: Value is 0.6, Tangible Net Worth: 7.88e+008, Min. Fixed Charge Coverage Ratio: Value is 1.75, Min. Debt Service Coverage Ratio: Value is 2.00

需要新增一列num_of_cov,统计每行financial_covenants中的契约数量(契约以逗号分隔),最终期望结果如下:

financial_covenantsnum_of_cov
Max. Debt to Cash Flow: Value is 6.001
Max. Debt to Cash Flow: Decreasing from 4.00 to 3.00, Min. Fixed Charge Coverage Ratio: Value is 1.202
Max. Debt to Cash Flow: Value is 3.001
Max. Debt to Cash Flow: Decreasing from 4.00 to 3.50, Min. Interest Coverage Ratio: Value is 3.002
Max. Leverage Ratio: Value is 0.6, Tangible Net Worth: 7.88e+008, Min. Fixed Charge Coverage Ratio: Value is 1.75, Min. Debt Service Coverage Ratio: Value is 2.004

请问如何用Python实现该需求?


解决方案

使用Python的pandas库可以高效完成这个需求,核心逻辑是按逗号(含后续空格)分割字符串,统计分割后的元素数量:

1. 导入库并加载数据

假设你的数据集是CSV格式,先读取数据(替换为你的实际文件路径):

import pandas as pd

df = pd.read_csv('your_dataset.csv')

2. 新增统计列

通过正则表达式匹配逗号加任意空格,分割每行的契约字符串,再获取分割后的元素个数:

# 分割并统计数量,自动处理逗号后的空格
df['num_of_cov'] = df['financial_covenants'].str.split(',\s*').str.len()

3. 处理空值(可选)

如果financial_covenants列存在空值,可添加以下逻辑将空值对应的契约数量设为0:

df['num_of_cov'] = df['financial_covenants'].apply(
    lambda x: len(str(x).split(',\s*')) if pd.notna(x) else 0
)

4. 验证结果

运行代码后,查看生成的列:

print(df[['financial_covenants', 'num_of_cov']])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 11:40:21