小编Fle*_*ers的帖子

将重复的“键=值”对的文件读入DataFrame

我有一个txt文件,其中包含此格式的数据。前三行重复一遍又一遍。

name=1
grade=A
class=B
name=2
grade=D
class=A
Run Code Online (Sandbox Code Playgroud)

我想以表格格式输出数据,例如:

name | grade | class
1    | A     | B
2    | D     | A
Run Code Online (Sandbox Code Playgroud)

我正在努力设置标头并仅遍历数据。到目前为止,我尝试过的是:

def myfile(filename):
    with open(file1) as f:
        for line in f:
            yield line.strip().split('=',1)

def pprint_df(dframe):
    print(tabulate(dframe, headers="keys", tablefmt="psql", showindex=False,))

#f = pd.DataFrame(myfile('file1')
df = pd.DataFrame(myfile('file1'))
pprint_df(df)
Run Code Online (Sandbox Code Playgroud)

该输出是

def myfile(filename):
    with open(file1) as f:
        for line in f:
            yield line.strip().split('=',1)

def pprint_df(dframe):
    print(tabulate(dframe, headers="keys", tablefmt="psql", showindex=False,))

#f = pd.DataFrame(myfile('file1')
df = pd.DataFrame(myfile('file1'))
pprint_df(df)
Run Code Online (Sandbox Code Playgroud)

并不是我真正想要的。

python pandas

10
推荐指数
3
解决办法
147
查看次数

标签 统计

pandas ×1

python ×1