【问题标题】:Pandas Python (read data without delimiter and header) [closed]Pandas Python(读取没有分隔符和标题的数据)[关闭]
【发布时间】:2020-11-30 03:18:05
【问题描述】:

我是 Python 新手

  1. 如何使用不带分隔符和标题的 pandas 读取这些数据?
  2. 如果我已经有了格式,如何分离和命名变量? eg: (Var name: Acc NO, length (13), type (num))

帮帮我!

样本数据:

 12345678912345NEWCUSTOMER               20201010ABC Enterprise    

我的预期输出是:

Acc NO              Type of Customer    Date         Name
12345678912345      NEW CUSTOMER        2020-10-10   ABC ENTERPRISE
                                             

【问题讨论】:

  • 你能再提供几行示例数据吗?不知道能不能概括一下

标签: python pandas variables delimiter separator


【解决方案1】:

这应该可行:

import pandas

# Some test data
data = """
12345678912345NEWCUSTOMER               20201010ABC Enterprise
12345678912345NEWCUSTOMER               20201010ABC Enterprise
12345678912345NEWCUSTOMER               20201010ABC Enterprise
"""

# Or read data from a file
with open("Customers.txt", "r") as file:
    data = file.read()

df = pandas.DataFrame(
    [
        {
            "Acc NO": line[0:14].strip(),
            "Type of Customer": line[14:40].strip(),
            "Date": line[40:48].strip(),
            "Name": line[48:].strip(),
        }
        for line in data.splitlines()
        if len(line) > 1
    ]
)
df["Date"] = pandas.to_datetime(df["Date"], format=r"%Y%m%d")

输出:

           Acc NO Type of Customer       Date            Name
0  12345678912345      NEWCUSTOMER 2020-10-10  ABC Enterprise
1  12345678912345      NEWCUSTOMER 2020-10-10  ABC Enterprise
2  12345678912345      NEWCUSTOMER 2020-10-10  ABC Enterprise

【讨论】:

  • 这是我读取文件的第一个代码:import pandas as pd fileName= 'Customers.txt' data = pd.read_csv("Customers.txt",sep="\t",header=None) pd.set_option('max_columns', None) data 所以结果是:0 0 12345678912345NEWCUSTOMER 20201010ABC Enterprise 1 32145678932192NEWCUSTOMER 20201009DEF Enterprise 但是当我尝试运行您的代码时,出现以下错误:' '对象没有属性'splitlines'
  • @AmyDiana,我已经更新了答案。您正在尝试使用 pandas 读取数据,但 pandas 无法解析格式。所以你必须按原样读取数据(只是纯文本),然后使用我的其余代码。
【解决方案2】:
import re
import pandas as pd


string='12345678912345NEWCUSTOMER               20201010ABC Enterprise'

items = []
for item in re.split('(\d+)', string):
    items.append(item.strip())
    
pd.DataFrame([items], columns=['index', 'Acc No', 'Type of Customer', 'Date', 'Name'])

正则表达式可以帮助您。 \d+ 匹配 1 个或多个数字。

【讨论】:

    猜你喜欢
    • 2015-11-22
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-01
    • 2013-09-26
    • 1970-01-01
    • 2017-11-25
    相关资源
    最近更新 更多