我的数据格式很不统一:
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中提取数据到pandas数据框=表的名称在后面列出,如Table_065。
我想我会阅读整个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变量后,它不再是字符串,而是列表等。 只是我需要帮助。 拜托,有谁可以帮助我吗? 谢谢!
答案 0 :(得分:0)
将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