[英]Merge Python Dataframe rows that are split in multiple rows
我正在使用 tabula-py 读取具有多个银行交易的 PDF。 将 PDF 转换为 CSV 得到:
但我需要它是:
基本上,描述有时是分裂的。
到目前为止,这就是我所做的:
import pandas as pd
import tabula
tabula.convert_into(
'input.pdf', 'output.csv', output_format="csv", pages="all"
)
df = pd.read_csv("./output.csv")
for index, row in df.iterrows():
datetime = row["datetime"]
try:
if pd.isnull(datetime) or (type(datetime) == list):
prefix = str(df.loc[index]["description"])
suffix = str(df.loc[index + 2]["description"])
df.at[index + 1, "description"] = prefix + " " + suffix
df.drop(index=index, inplace=True)
df.drop(index=index + 2, inplace=True)
except KeyError:
pass
print(df)
到目前为止,我已经让它与我提供的解决方案一起工作。 但问题是这非常慢,我必须为每个客户处理成千上万的交易,处理成千上万的客户,这需要很长时间。 我在想也许我可以使用df.apply()
但我不能完全理解在当前行之后访问行。
这是 CSV:
datetime,description,debit,credit,balance
2018-08-27 08:18 AM,Buy RAM,75.00,,5535.50
,Buy MSI RTX 3080,,,
2018-08-27 05:12 PM,,3000.00,,2539.25
,VENTUS 3X 10G OC graphics,,,
2018-08-28 03:46 PM,Salary,,5.00,2444.25
2018-08-28 03:46 PM,Buy Oranges,100.00,,2439.25
2018-08-28 08:00 PM,Project Compensation,,8550.00,10994.25
2018-08-28 08:04 PM,Buy Tesla Stock,2000.00,,8994.25
,Buy Logitech G502,,,
2018-08-29 10:47 AM,,5900.00,,3094.25
,HERO High Performance Gaming Mouse,,,
,Buy Extra Spicy,,,
2018-08-29 03:58 PM,,628.00,,2466.25
,Tacos,,,
PS 我无法控制 PDF 的格式,因为 PDF 来自银行,并且它们没有我可以使用的外部 API。
我知道这并不完全理想,但这是做一些接近你需要的事情的一种方法
>>> df['datetime'] = pd.to_datetime(df['datetime']).ffill()
>>> df.fillna('').groupby('datetime').agg(list)
description debit credit balance
datetime
2018-08-27 08:18:00 [Buy RAM, Buy MSI RTX 3080] [75.0, ] [, ] [5535.5, ]
2018-08-27 17:12:00 [, VENTUS 3X 10G OC graphics] [3000.0, ] [, ] [2539.25, ]
2018-08-28 15:46:00 [Salary, Buy Oranges] [, 100.0] [5.0, ] [2444.25, 2439.25]
2018-08-28 20:00:00 [Project Compensation] [] [8550.0] [10994.25]
2018-08-28 20:04:00 [Buy Tesla Stock, Buy Logitech G502] [2000.0, ] [, ] [8994.25, ]
2018-08-29 10:47:00 [, HERO High Performance Gaming Mouse, Buy Ext... [5900.0, , ] [, , ] [3094.25, , ]
2018-08-29 15:58:00 [, Tacos] [628.0, ] [, ] [2466.25, ]
我想你可以进一步“按摩”它以获得完全需要的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.