【发布时间】:2019-11-06 04:00:00
【问题描述】:
这是我拥有的 I 数据的一个类似示例,但行数要少得多。
假设我有一个这样的 txt 文件:
'''
Useless information 1
Useless information 2
Useless information 3
Measurement:
Len. (cm) :length of the object
Hei. (cm) :height of the object
Tp. :type of the object
~A DATA
10 5 2
8 7 2
5 6 1
9 9 1
'''
并且我想将 '~A DATA' 下面的值作为 DataFrame。如您所见,我已经设法获得了没有列名的 DataFrame(尽管它有点乱,因为我的代码中有一些废话):
with open(r'C:\Users\Lucas\Desktop\...\text.txt') as file:
for line in file:
if line.startswith('~A'):
measures = line.split()[len(line):]
break
df = pd.read_csv(file, names=measures, sep='~A', engine='python')
newdf = df[0].str.split(expand = True)
newdf()
0 1 2
0 10 5 2
1 8 7 2
2 5 6 1
3 9 9 1
现在,我想将文本中的“Len”、“Hei”和“Tp”作为列名放在 DataFrame 上。只是这些测量代码(没有相应的字符串)。我怎样才能拥有这样的 df?
Len Hei Tp
0 10 5 2
1 8 7 2
2 5 6 1
3 9 9 1
其中一个解决方案是将字符串“Measurement”下方的每一行(或从“Len...”行开始)拆分到字符串“~A”上方的每一行(或以“Tp”行结尾)。然后拆分我们得到的每一行。但我不知道该怎么做。
【问题讨论】:
-
df.columns = ['Len','Hei','Tp'] -
这能回答你的问题吗? Renaming columns in pandas
-
对不起,伙计们。我需要从文本的字符串中获取列名,因为原始文件有数千行,我不能一一写。
标签: python-3.x pandas text split strip