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

Excel数据处理中Securities_CUSIP列输出时数值丢失的问题求助

Excel数据处理中Securities_CUSIP列输出时数值丢失的问题求助

看起来你遇到了一个挺闹心的问题:明明读取Excel文件时Securities_CUSIP列是有有效数据的,但经过代码处理后输出到新Excel里,这列的数值就不见了。你怀疑和dropna或者数值/非数值列的处理有关,这个方向是对的,我帮你揪出代码里的问题所在~

问题根源分析

你代码里有一行关键的错误操作,直接导致了Securities_CUSIP列的数据丢失:

df_selected = df_selected.apply(pd.to_numeric, errors = 'coerce')

这行代码会对整个DataFrame的所有列尝试转换为数值类型,而Securities_CUSIP是字符串类型(通常包含字母+数字的组合,并非纯数值),转换时会被强制转为NaN,最终输出到Excel里就变成了空值。

而你之前其实已经正确处理了数值列:

numeric_cols = [col for col in selected_columns if col != 'Securities_CUSIP']
if numeric_cols:
    df_selected[numeric_cols] = df_selected[numeric_cols].apply(pd.to_numeric, errors = 'coerce')

这部分已经单独把除了Securities_CUSIP之外的列转为数值型,完全不需要再对整个DataFrame做一次全量的数值转换操作。

修正后的代码

只需要把那行错误的全量转数值代码删掉就可以解决问题,修正后的核心代码段如下:

selected_columns = ['Securities_CUSIP', 'SecurityTransactions_PriceBloomberg', 'SecurityTransactions_PriceIDC',            'SecurityTransactions_PriceReuter', 'SecurityTransactions_PriceMarkit', 'SecurityTransactions_PriceSP']

updated_sheets = {}

for sheet_name, df in all_sheets.items():
    if 'Securities_CUSIP' in df.columns:
        df_selected = df[selected_columns].copy()
        df_selected['Securities_CUSIP'] = df_selected['Securities_CUSIP'].astype(str).fillna("")
        # df_selected.dropna(subset = ['Securities_CUSIP'], inplace = True)
        numeric_cols = [col for col in selected_columns if col != 'Securities_CUSIP']
        if numeric_cols:
            df_selected[numeric_cols] = df_selected[numeric_cols].apply(pd.to_numeric, errors = 'coerce')
        # 删掉下面这行错误的全量转数值代码
        # df_selected = df_selected.apply(pd.to_numeric, errors = 'coerce')
        df_selected['Max Value'] = df_selected.max(axis = 1, skipna = True)
        df_no_zeros = df_selected.replace(0, np.nan)
        df_selected['Min Value'] = df_no_zeros.min(axis = 1, skipna = True)
        df_selected['Max Range'] = df_selected['Max Value'] - df_selected['Min Value']
        updated_sheets[sheet_name] = df_selected
    else:
        print(f"Skipping {sheet_name}: Selected columns not found.")
print("\n" + "-"*50 + "\n")
with pd.ExcelWriter(output_file, engine = 'xlsxwriter') as writer:
    for sheet_name, df in updated_sheets.items():
        df.to_excel(writer, sheet_name = sheet_name, index = False)
print(f"Updated Excel file saved as: {output_file}")

额外注意事项

  • Securities_CUSIP作为标识性的字符串列,一定要保持其字符串类型,不要尝试转为数值型,否则会丢失非数字部分的信息。
  • 如果后续需要对Max Value等计算列做数值操作,因为之前已经处理过所有数值列,所以这些计算会正常进行,不会受字符串列的影响。

备注:内容来源于stack exchange,提问作者user30112988

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 20:18:11