从.txt填充pandas数据帧,从多个.txt行读取单个数据帧行信息

问题描述 投票:1回答:2

我想从一个大的.txt中读入一个pandas数据帧信息,该信息以下列形式排列:

    elm1 x1 x2 x3 
    cont x4 x5 x6
    cont x7 x8
    elm2 x9 x10 x11
    cont x12 x13 x14
    cont x15 x16 
....

数据框应按以下方式排列:

elm_ID col1 col2 col3 col4 col5 col6 col7 col8
elm_1 x1 x2 x3 x4 x5 x6 x7 x8
elm_2 x9 x10 x11 x12 x13 x14 x15 x16
.......

有人有点想法吗?非常感谢提前。

J.A.

python pandas numpy
2个回答
0
投票

是的,您可以轻松地将数据转换为数据帧。首先,我们通过逐行读取文本文件中的数据来创建我们需要转换为数据帧的数据列表:

import re

df_list = [] #as you want these as your headers 
with open(infile) as f:
    for line in f:
        # remove whitespace at the start and the newline at the end
        line = line.strip()
        # split each column on whitespace
        columns = re.split('\s+', line, maxsplit=4)
        df_list.append(columns)

然后我们可以使用简单地将此列表转换为数据帧

import pandas as pd
df = pd.DataFrame(df_list,columns=[elm_ID col1 col2 col3 col4 col5 col6 col7 col8])

-1
投票

首先,通过pd.read_csv(path_to_file, sep='\t')读取txt文件。

然后,假设我们有这个数据帧:

      a    b    c
0  elm1   x1   x2
1  cont   x4   x5
2  cont   x7   x8
3  elm2   x9  x10
4  cont  x12  x13
5  cont  x15  x16

我们想要这个输出:

       0    1    2    3    4    5                      
elm1  x1   x4   x7   x2   x5   x8
elm2  x9  x12  x15  x10  x13  x16

我尝试使用pandas函数完全解决它:

df = pd.DataFrame([("elm1", "x1", "x2" ),
    ("cont", "x4", "x5"),
    ("cont", "x7", "x8"),
    ("elm2", "x9", "x10"),
    ("cont", "x12", "x13"),
    ("cont", "x15", "x16")] , columns=list('abc'))
df['d'] = df['a'] != 'cont'
df['e'] = df['a']
df['e'][~df['d']] = np.nan
df['e'] = df['e'].fillna(method='ffill')
df2 = df.groupby('e').apply(lambda x: pd.concat([x['b'], x['c']])).to_frame().reset_index()
df2['ct'] = df2.reset_index().groupby('e').cumcount()
df3 = df2.pivot(index='e', values=[0], columns='ct')
df3.columns = range(len(df3.columns))
df3.index.name = ''
© www.soinside.com 2019 - 2024. All rights reserved.