将文本文件上传到熊猫数据框

时间:2020-04-03 19:56:05

标签: python pandas list dataframe text

我在处理过程中遇到麻烦,之前我曾做过几次重复。我是Python和Jupyter笔记本的新用户,并且我试图转换包含以下数据的文本文件:(25k个列表):

[X,
Y],
[Z,
X,
Y,
Z],

这是文件结构,我正在尝试使用以下代码将其转换为熊猫数据框(宽列存储):

import pandas as pd
import ast
import json 

data = open("C:/Users/itamar/Desktop/SuperMushlam/How To Use Apriori Algorithm A-Z/sss.txt", 'r', encoding = 'windows-1255', errors='ignore').read().replace("\r","").replace("\n","")

remove_doulequotes = data.replace('""', '').replace('"', '')

list_of_str = list(map(lambda x: '"{x}"'.format(x=x), remove_doulequotes.split(",")))

final_data = ", ".join(list_of_str).replace('"[[', '[["').replace(']"','"]').replace(']]"', '"]]').replace('"[', '["').replace(']"]', '"]]')

data_in_list = ast.literal_eval(final_data)

df = pd.DataFrame(data_in_list)

df

它曾经工作过,所以我试图了解在此过程中我的问题在哪里。 这是我收到的错误消息:

    ---------------------------------------------------------------------------
MemoryError                               Traceback (most recent call last)
<ipython-input-10-d41ed8f6586e> in <module>
     11 final_data = ", ".join(list_of_str).replace('"[[', '[["').replace(']"','"]').replace(']]"', '"]]').replace('"[', '["').replace(']"]', '"]]')
     12 
---> 13 data_in_list = ast.literal_eval(final_data)
     14 
     15 df = pd.DataFrame(data_in_list)

~\Anaconda3\lib\ast.py in literal_eval(node_or_string)
     44     """
     45     if isinstance(node_or_string, str):
---> 46         node_or_string = parse(node_or_string, mode='eval')
     47     if isinstance(node_or_string, Expression):
     48         node_or_string = node_or_string.body

~\Anaconda3\lib\ast.py in parse(source, filename, mode)
     33     Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
     34     """
---> 35     return compile(source, filename, mode, PyCF_ONLY_AST)
     36 
     37 

MemoryError: 

有什么建议吗?我不确定我的问题在哪里。非常感谢!

那是我需要的:

enter image description here

1 个答案:

答案 0 :(得分:0)

假设您的整个文本文件与您描述的模式匹配:

[X,
Y],
[Z,
X,
Y,
Z],

您可能可以通过以下代码构建所需的DataFrame:

import pandas as pd

df_l = []
tmp_l = []
filename = "C:/Users/itamar/Desktop/SuperMushlam/How To Use Apriori Algorithm A-Z/sss.txt"
with open(filename) as f:
    for line in f:
        value = ''.join([c for c in line if c not in '[ ] ,'.split()]).strip('\n')
        value = float(value) if value.replace('.','',1).isdigit() else value
        tmp_l.append(value)
        if ']' in line:
            df_l.append(pd.DataFrame(tmp_l).T)
            tmp_l = []

df = pd.concat(df_l, ignore_index=True)
print(df)

输出:

   0  1    2    3
0  X  Y  NaN  NaN
1  Z  X    Y    Z

Process finished with exit code 0

上述解决方案列出了一个单行DataFrame(df_l)的列表,其中每个DataFrame是从.txt文件中的每个列表创建的。他们使用pd.concatdf_l中的所有那一行DataFrame合并为一个df。此解决方案还假设您的.txt文件的每一行仅包含一个列表项,并且字符"["",""]"将不包含在该列表项中。