numpy 在python中,将文件中的不同数据(以空行分隔)拆分到不同的列表中

y1aodyip  于 11个月前  发布在  Python
关注(0)|答案(2)|浏览(92)

Python新手在这里,我有一个文件,其中包含不同的物理实验,由一个空白行划分,为:

#t x
0 0
0 1
0 2

0 1
0 2
0 3

字符串
我想知道是否有一个简单的方法来分割我的数据在多个列表中,基于关闭列和实验(列表t1为第一个实验的时间,等等。),这样我就可以分别绘制不同的实验。
我尝试了numpy.loadtxtpandas.read_csv,但它们只是跳过空白行并合并所有数据。我搜索了类似c fscanf函数的东西,在空白行停止,但我找不到一个简单的方法。

iaqfqrcu

iaqfqrcu1#

在阅读数据时没有直接的方法来分割,但是你可以读取整个文件并利用空白行来分割框架:

df = pd.read_csv('your_file.csv', sep=r'\s+', skip_blank_lines=False)

m = df.isna().all(axis=1)

dfs = [g for _,g in df[~m].groupby(m.cumsum())]

print(dfs)

字符串
输出量:

[    #t    x    # DataFrame #1
 0  0.0  0.0
 1  0.0  1.0
 2  0.0  2.0,
     #t    x    # DataFrame #2
 4  0.0  1.0
 5  0.0  2.0
 6  0.0  3.0]

ru9i0ody

ru9i0ody2#

# Read file
with open('filename.txt', 'r') as f:
    raw_data = f.read()

# Seperate each experiment
experiments = raw_data.split('\n\n')

# Split lines
experiments = [lines.split('\n') for lines in experiments]

# Create empty list for all.
all_data = []

for experiment in experiments:
    # Create empty list for each experiment.
    data = {'t':[], 'x':[]}
    for line in experiment:

        # if the first character of line is not a number, ignore ( for #t, x )
        if (not line[0].isdigit()): continue
        
        # split and convert data into int
        t, x = map(int,line.split(' '))

        # append it
        data['t'].append(t)
        data['x'].append(x)

    # append it
    all_data.append(data)

字符串

相关问题