【问题标题】:strings to column using python使用python将字符串转换为列
【发布时间】:2020-01-30 10:33:08
【问题描述】:

我将整个表格作为字符串,如下所示: a= "id;date;type;status;description\r\n1;20-Jan-2019;cat1;active;customer is under\xe9e 观察\r\n2;18-Feb-2019;cat2;active;customer is正版\r\n"

在字符串内部,我们确实有一些 ascii 代码,例如 \xe9e,所以我们必须将字符串转换为非 ascii

我的预期输出是将上面的字符串转换为数据框 如下:

id date       type status description
1 20-Jan-2019 cat1 active customer is under observation
2 18-Feb-2019 cat2 active customer is genuine

我的代码:

b = a.splitlines()
c = pd.DataFrame([sub.split(";") for sub in b])

我得到以下输出。但我需要第一行作为我的标题,并将 ascii 转换为 utf-8 文本。

        0   1           2           3   4                               5  6
    0   id  date        type    status  description                     None  None
    1   1   20-Jan-2019 cat1    active  customer is underée observation None  None
    2   2   18-Feb-2019 cat2    active  customer is genuine             None  None

另外,请不要在这里创建值为 None 的额外列。不应该是这样的

【问题讨论】:

  • 您尝试过什么,遇到了什么具体问题?
  • c.columns = c.iloc[0],然后是c = c.iloc[1:].reset_index(drop=True)
  • @Erfan 我错过了一行要在此处更新,它正在创建具有值 None 的额外列
  • None 还是NaN

标签: python string pandas python-2.7


【解决方案1】:

这是一个有点老套的答案,但鉴于您的问题不是很清楚,这应该就足够了。

 import pandas as pd
 import numpy as np
 import re

 a="id;date;type;status;description\r\n1;20-Jan-2019;cat1;active;customer is under\xe9e observation\r\n2;18-Feb-2019;cat2;active;customer is genuine\r\n"

 b=re.split('; |\r|\n',a) #split at the delimiters.

 del b[-1] #also delete the last index, which we dont need
 b[1:]=[re.sub(r'\xe9e', '', b[i]) for i in range(1,len(b))]  #get rid of that \xe9e issue

 df=pd.DataFrame([b[i].split(';') for i in range(1,len(b))]) #make the dataframe
 ##list comprehension allows to generalize this if you add to string##
 df.columns=b[0].split(';') #split the title words for column names
 df['id']=[i for i in range(1,len(b))]
 df

这个输出大概就是你所说的数据框的意思:

【讨论】:

  • 您的代码将被限制为两行,因为您特别提到了 b=re.split('; |\r|\n1|\n2|\n',a) 但我需要它一个大文件
  • 你可能应该在你的问题中提到这一点......我已经更新了解决方案,但这应该可以帮助你
猜你喜欢
  • 2015-04-14
  • 2016-11-09
  • 1970-01-01
  • 2023-03-16
  • 2014-07-25
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 2017-11-15
相关资源
最近更新 更多