这是我所拥有的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'行结尾) 。然后拆分我们得到的每一行。但是我不知道该怎么做。
解决方案1:如果要从文本文件本身中删除列名,则需要知道列名信息从哪一行开始,然后读取文件行-按行并针对您知道具有列名称作为文本的特定行进行处理。
为了回答您所问的特定问题,我们假设变量line
包含字符串之一,例如line = Len. (cm) :length of the object
,您可以进行基于正则表达式的拆分,其中,您可以拆分除数字和字母之外的任何特殊符号。
import re
splited_line = re.split(r"[^a-zA-Z0-9]", line) #add other characters which you don't want
print(splited_line)
这导致
['Len', ' ', 'cm', ' ', 'length of the object']
此外,要获取列名,请从列表中选择第一个元素为splited_line[0]
解决方案2:如果您已经知道列名,则可以这样做
df.columns = ['Len','Hei','Tp']