futui 发表于 2023-3-27 18:48:25

列表套列表怎么转变成数据帧,求大师帮忙

先谢谢大侠,下面是我的需求:


webpage.txt文本内容如下:
var r = [["000001","HXCZHH","华夏成长混合","混合型-灵活","HUAXIACHENGZHANGHUNHE"],["000002","HXCZHH","华夏成长混合(后端)","混合型-灵活","HUAXIACHENGZHANGHUNHE"],["000003","ZHKZZZQA","中海可转债债券A","债券型-可转债","ZHONGHAIKEZHUANZHAIZHAIQUANA"],["980003","TPYLGYGDCYZ","太平洋六个月滚动持有债","债券型-长债","TAIPINGYANGLIUGEYUEGUNDONGCHIYOUZHAI"]];


我想用下面方法提取列表:
with open(r'C:\Users\ppp\Desktop\webpage.txt', "r") as f:      
    #print(type(f))
    response= f.read()

data_list = re.findall(r'\[(.*?)\]',response)


上面这个方法提不出,要怎么才能从桌面文本webpage.txt中 ,提取出列表data_list:
data_list = [["000001","HXCZHH","华夏成长混合","混合型-灵活","HUAXIACHENGZHANGHUNHE"],["000002","HXCZHH","华夏成长混合(后端)","混合型-灵活","HUAXIACHENGZHANGHUNHE"],["000003","ZHKZZZQA","中海可转债债券A","债券型-可转债","ZHONGHAIKEZHUANZHAIZHAIQUANA"],["980003","TPYLGYGDCYZ","太平洋六个月滚动持有债","债券型-长债","TAIPINGYANGLIUGEYUEGUNDONGCHIYOUZHAI"]]


df = pd.dataframe(data_list,columns=["代码" ,"名称首字拼音","名称","类型", "其它"])

我最终要的结果是下面这个样子:
代码               名称首字拼音    名称             类型                                          其它                                 
"000001"   HXCZHH"            "华夏成长混合"                  "混合型-灵活"      "HUAXIACHENGZHANGHUNHE"
"000002""HXCZHH"            "华夏成长混合(后端)"         "混合型-灵活"      "HUAXIACHENGZHANGHUNHE"
"000003"ZHKZZZQA"          "中海可转债债券A"             "债券型-可转债"   "ZHONGHAIKEZHUANZHAIZHAIQUANA"
"980003""TPYLGYGDCYZ"   "太平洋六个月滚动持有债"   "债券型-长债"      "TAIPINGYANGLIUGEYUEGUNDONGCHIYOUZHAI"

isdkz 发表于 2023-3-27 18:56:05

import re
import pandas as pd

with open(r'C:\Users\ppp\Desktop\webpage.txt', "r") as f:      
    #print(type(f))
    response= f.read()

data_list = re.findall(r'\[(?:.*)\]', response)

df = pd.DataFrame(data_list, columns=["代码" ,"名称首字拼音","名称","类型", "其它"])

futui 发表于 2023-3-27 21:44:10

大师,不知什么原因,报错

Traceback (most recent call last):
File "D:\Synchronization\OneDrive\Investment\Accounts\python\test_temp\temp_test.py", line 10, in <module>
    df = pd.DataFrame(data_list, columns=["代码" ,"名称首字拼音","名称","类型", "其它"])
File "C:\Users\cenghua\anaconda3\lib\site-packages\pandas\core\frame.py", line 756, in __init__
    raise ValueError("DataFrame constructor not properly called!")
ValueError: DataFrame constructor not properly called!
页: [1]
查看完整版本: 列表套列表怎么转变成数据帧,求大师帮忙