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

Python列表转换为pandas DataFrame时数据堆积在单行问题排查

问题原因

你的highlights列表本身仅包含1个长字符串元素,所有逗号分隔的内容都包含在这一个字符串内,所以查询列表长度返回1,直接转换为DataFrame自然所有内容都集中在同一行。操作错误点在于没有先将长字符串按逗号分割为独立的元素列表。

解决方法

先对highlights中的长字符串按逗号分割,再转换为DataFrame即可,示例代码如下:

import pandas as pd

# 原始highlights列表
highlights = ['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']

# 取出长字符串按逗号分割,同时去除每个元素前后的多余空格
split_data = [item.strip() for item in highlights[0].split(',')]

# 转换为DataFrame
df = pd.DataFrame(split_data, columns=['C-Names'])

print(df)

如果后续需要把证券名称和净资产占比拆分为独立列,可追加以下代码:

# 从右侧拆分1次,避免名称本身带空格导致拆分错误
df[['Security Name', 'Net Assets Percentage']] = df['C-Names'].str.rsplit(n=1, expand=True)

内容的提问来源于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 21:06:04