如何仅将一个列表更改为包含许多列的数据框

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

我在网上抓了一些数据并将它们保存在记事本中作为文本。现在我想对这些数据进行分析,但意识到只有一列。

由于文本文件是在漂亮的表中完成的,因此我无法拆分数据。

The text file looks like this. 
                                                 0
0  +-------------+------+--------+---------+-----...
1  |  series id  | year | period |  value  | foot...
2  +-------------+------+--------+---------+-----...
3  | CUUR0000SA0 | 2014 |  M12   | 234.812 |     ...
4  | CUUR0000SA0 | 2014 |  M11   | 236.151 |     ...

即使表格看起来有五列,但当我检查形状时,实际上只有一列。任何人都可以帮助如何将其转移到数据框中的五列?

python pandas dataframe pretty-print
1个回答
0
投票

这是一种实现此目的的方法:

import pandas as pd

# Sample text file (stored as a single string)
text = '''                                                 0
0  +-------------+------+--------+---------+
1  |  series id  | year | period |  value  |
2  +-------------+------+--------+---------+
3  | CUUR0000SA0 | 2014 |  M12   | 234.812 |
4  | CUUR0000SA0 | 2014 |  M11   | 236.151 |'''

# Parse the text file
lst = text.replace('+', '').replace('-', '').replace('|', '').split('\n')
new_lst = [lst[2]] + lst[4:] # Grab the data around the empty rows

# Build the data frame
df = pd.DataFrame(new_lst) # Create data frame from list
df = df[0].str.split(expand=True) # Split data into columns
df.columns = df.iloc[0,:] # Name the columns
df = df[1:] # Remove the first row
df = df[df.columns[1:]] # Remove the first column
df = df.reset_index(drop=True)
print(df)
0       series    id year   period value
0  CUUR0000SA0  2014  M12  234.812  None
1  CUUR0000SA0  2014  M11  236.151  None

您可能需要稍微调整一下才能使用实际数据。

你可能会在你的文本文件中读到这样的:

with open('file.txt') as f:
    lines = f.readlines()

您可以使用text = '\n'.join(lines)然后继续执行上述其余脚本。

© www.soinside.com 2019 - 2024. All rights reserved.