简体   繁体   English

读取csv文件以列出

[英]Read csv file to list

I want to export a nested list, then import it without losing the shape of the list. 我想导出一个嵌套列表,然后在不丢失列表形状的情况下将其导入。 The list is a nested list, each inner list has 10 elements, there are 10000 inner lists construct a large list. 该列表是一个嵌套列表,每个内部列表有10个元素,有10000个内部列表构成一个大列表。

The inner lists look like this: the shape is 1 x 10 内部列表如下所示:形状为1 x 10

    [array([  1, 2, 3, 4, 5
              6, 7, 8, 9, 10 ],
    array([ 21, 22, 23, 24, 25
           26, 27, 28, 29, 30 ]

I exported it to csv. 我将其导出到csv。 In csv, it becomes like this. 在csv中,它变成这样。 Each inner list is in one cell 每个内部列表在一个单元格中

['[ 1  2  3  4  5\n 6  7  8  9  10]']
['[ 21  22  23  24  25\n 26  27  28  29  30]']

Then I imported the csv to list. 然后,我将csv导入列表。 However the shape becomes 1 x 1 I wish to make it into 1 x 10 shape, ideally same as the original list format I exported. 但是,形状变为1 x 1,我希望将其制成1 x 10形状,理想情况下与我导出的原始列表格式相同。 how to achieve this ? 如何实现呢?

The code I used for exporting list: (X is the list) 我用于导出列表的代码:(X是列表)

import csv
with open('X.csv', "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    for val in X:
        writer.writerow([val])  

The code I used for importing csv: (X is the list) 我用于导入csv的代码:(X是列表)

with open('X.csv', 'r') as f:
    reader = csv.reader(f)
    X = list(reader)

Thank you in advanced ! 在此先感谢您!

Try This, 尝试这个,

import pandas as pd
df = pd.read_csv('filename.csv')
list_ = df.values.tolist()

I would suggest you maybe save it as a pickle or a DataFrame instead to you don't need to fiddle about so much when reading it back in. Pickles save in the memory representation used by python. 我建议您也许将其保存为泡菜或DataFrame,而不是因为读回时不需要花太多时间。泡菜保存在python使用的内存表示中。

import pickle
pickle.dump(X, open('X.pkl', "wb"))
X_loaded = pickle.load(open('X.pkl', "rb"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM