繁体   English   中英

从.txt填充熊猫数据框,从多条.txt行读取单个数据框行信息

[英]Populate pandas dataframe from .txt reading single dataframe row information from multiple .txt lines

我想从大的.txt文件中读取熊猫数据框信息,该信息以以下形式排列:

    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
.......

有人有主意吗? 非常感谢。

JA

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

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])

首先,通过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 = ''

暂无
暂无

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

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