将特定的csv列读取到数组中(Python)

时间:2018-09-26 02:11:20

标签: python-3.x file-io

所以我有一个像这样的数据列表:

"Load (lbf)","Time (s)","Extension (in)","Stress (ksi)","Strain (in/in)"

103.2,0.30,0.008,1.160,0.00228
172.4,0.50,0.009,1.939,0.00246
241.8,0.70,0.010,2.718,0.00264
311.2,0.90,0.010,3.500,0.00282...

我本质上想做的是将其转换为制表符分隔的表,以便可以将其复制粘贴到origin或excel中。这样做的计划是将每一列读入一个数组,并用制表符作为分隔写回去。问题是我没有编写代码的正式培训,而且几个月后我还没做过,所以阅读SE并不是特别有帮助(很少有人会逐行解释他们的代码做什么。)碰到正在读取的数据似乎不想播放。我尝试过:

file=str(input("enter filepath: "))
hdr=int(input("enter number of lines before data: "))
def read(file, convert=float, sep=","):
    with open(file) as f:
        for i in range(hdr):
            next(f)

        for line in f:
            load.append(col[1])

以及:

file=str(input("enter filepath: "))
hdr=int(input("enter number of lines before data: "))
def read(file, convert=float, sep=","):
     with open(file) as f:
        for i in range(hdr):
            next(f)
        for line in f:

          extension.append[convert(line.split(sep=',')[3]) for line in f]

没有引发任何错误,但是它什么也没做。任何提示都将大有帮助。

1 个答案:

答案 0 :(得分:1)

您可能想利用pandas软件包,该软件包专门处理和处理数据。 特别是,有一个read_csv函数可以接收一个csv并将其保存为DataFrame(Panda的数据结构)。然后,您可以将其重新输出为另一个csv,但这一次,将分隔符指定为制表符\t

import pandas as pd
data = pd.read_csv('data.csv')  # load dataset into a Pandas dataframe
data.head()  # inspect first 5 rows in your dataset to make sure all is well
data.to_csv('new_data.csv', sep='\t', index=False)  # output with tab separated values