将文本文件拆分为多个文件并上载到数据帧

2024-06-02 04:34:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据格式很不好:

 Table                501

 ----------------------------------------------------------------
 |Sale|Di|Dv|Cus |Mat         |Valid From|Valid to  |
 ----------------------------------------------------------------
 |88|01|02|dd|20300    |24.05.2012|31.12.9999|
 |889|01|02|dd|20300     |24.05.2012|31.12.9999|
 |890|01|02|dd|20300     |24.05.2012|31.12.9999|
 ----------------------------------------------------------------

  Table                55

 ---------------------------------------------------------
 |Sale|Di|Dv|Cus  |Grou|S|Valid From|Valid to  |
 ---------------------------------------------------------
 |4500|44|55|A|01560    | |11.02.2019|31.12.9999|
 |4500|44|55|BBB|55070    | |30.04.2018|31.12.9999|
 |4500|44|55|D|55080    | |30.04.2018|31.12.9999|
 |4500|44|55|D|55420    | |30.04.2018|31.12.9999|
 |4500|44|55|8834496   |55450    | |30.04.2018|31.12.9999|
 ---------------------------------------------------------

  Table                065

 ----------------------------------------------------------------
 |Sale|Di|Dv|Cus  |Mat         |Valid From|Valid to  |
 ----------------------------------------------------------------
 |4500|44|55|bbbb   |01000     |29.05.2013|31.12.9999|
 ----------------------------------------------------------------

我想用python从这个txt文件中提取数据,将dataframes=表的名称列在后面,如表\u065。你知道吗

我想我应该读取整个txt并将其拆分为多个txt,替换以“-%”和“%”开头的行,然后将其作为单个表上载。你知道吗

但我很快就被卡住了:

file = open('0400.txt', 'r')
a = [n for n in file.readlines() if not n.startswith(' -') ]
#a = str(a)
#b = [n for n in a.readlines() if not n.startswith(' ') ]

似乎在使用a变量之后,它不再是字符串,而是列表等。 我只是需要帮助。 请问,有人能帮我吗? 谢谢!你知道吗


Tags: toinfromtxtfortablesaledd
1条回答
网友
1楼 · 发布于 2024-06-02 04:34:48

在将9999年转换为datetime对象时,尝试一些操作和错误处理

import pandas as pd

with open("0400.txt", "r") as f:
    lines = [
        [y.strip() for y in x.split("|")] 
        for x in f.readlines() if not x.startswith(" -")]

df = pd.DataFrame(lines[1:], columns=lines[0])
df["Valid to"] = pd.to_datetime(df["Valid to"], errors="coerce").fillna(pd.Timestamp.max.date())
df["Valid From"] = pd.to_datetime(df["Valid From"], errors="coerce")
print(df)

     Sale  Di  Dv      Cus    Mat Valid From    Valid to  
0    0400  01  02  1327260  20300 2012-05-24  2262-04-11  
1    0400  01  02  1327260  20300 2012-05-24  2262-04-11  
2    0400  01  02  1327260  20300 2012-05-24  2262-04-11  

相关问题 更多 >