【问题标题】:How to separate specific strings from a text and add them as column names?如何从文本中分离特定字符串并将它们添加为列名?
【发布时间】: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


【解决方案1】:

解决方案 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']

这里是您正在寻找的完整解决方案:

In [34]: f = open('text.txt', "rb") 
    ...: flag = False 
    ...: column_names = [] 
    ...: for line in f: 
    ...:     splited_line = re.split(r"[^a-zA-Z0-9~]", line.decode('utf-8')) 
    ...:     if splited_line[0] == "Measurement": 
    ...:         flag = True 
    ...:         continue 
    ...:     elif splited_line[0] == "~A": 
    ...:         flag = False 
    ...:     if flag == True: 
    ...:         column_names.append(splited_line[0]) 

【讨论】:

  • 感谢您的宝贵时间,@Anant Mittal。但我仍然需要一个不同的解决方案。答案应该是我需要将字符串“Measurement”下方的每一行(或从“Len ...”行开始)拆分到字符串“~A”上方的每一行(或以“Tp”行结尾)。然后对我们得到的每一行进行拆分。你能帮帮我吗?
  • 是的。这将是一个巨大的帮助;)
  • 是的。这些行并不重要
  • 给我时间,我在工作。确认一下,这就是正确的文件结构吧? Measurement: Len. (cm) :length of the object Hei. (cm) :height of the object Tp. :type of the object ~A DATA这正是文件的内容?
  • 是的。想象从“无用信息 1”到“~A DATA”的行作为文件的标题,它们下面的数字作为我想要的值。然后我需要选择并拆分以“Len...”、“Hei...”和“Tp...”开头的行,以将列名中的第一个字符串转换为 DataFrame。
猜你喜欢
  • 1970-01-01
  • 2022-01-21
  • 2014-11-27
  • 2016-02-08
  • 1970-01-01
  • 2014-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多