请求协助:将Finanzblick导出CSV数据按金额正负拆分至Inflow/Outflow
Hey Phil, let's break down what's going wrong with your code and fix it up properly:
1. 不必要且精度丢失的整数转换
You've got this line in your code:
Betrag = df.Betrag.astype(int)
This is totally unnecessary, and worse—it truncates decimal values (like 19.34) down to whole numbers (19), losing critical precision for your financial data. Just delete this line entirely; we need to keep the original floating-point values in df.Betrag.
2. Invalid HTML escape characters
Your code uses > and < (HTML escape codes for > and <), which Python doesn't recognize as valid comparison operators. Replace these with the standard > and < symbols to avoid syntax errors.
3. Type confusion from empty strings
Setting non-matching values to "" (empty string) turns your Inflow and Outflow columns into object type (mixing numbers and strings), which will cause headaches if you try to do any numerical calculations later, or even when importing into YNAB. A better approach is to use np.nan (pandas' standard missing value marker), which keeps the columns as numerical types and will export as empty cells in your CSV.
Fixed Full Code
import pandas as pd import numpy as np # Read the CSV with your original configuration df = pd.read_csv( "C:/Users/PD/Desktop/Finanzblick Dokumente/2017_11/2017_11- DB.csv", sep=';', usecols=(0,1,2,3,4), encoding='utf-8', decimal=',' ) # Rename columns to your desired labels df.columns = ['Date', 'Payee', 'Verwendungszweck', 'Buchungstext', 'Betrag'] # Combine memo fields (this part was already correct!) df['Memo'] = df[['Buchungstext', 'Verwendungszweck']].apply(lambda x: ' -- '.join(x), axis=1) # Correct inflow/outflow logic with valid operators and proper missing values df['Inflow'] = np.where(df.Betrag > 0, df.Betrag, np.nan) df['Outflow'] = np.where(df.Betrag < 0, df.Betrag * (-1), np.nan) # Export the cleaned CSV df.to_csv( 'C:/Users/PD/source/repos/Finanzblick YNAB/Finanzblick YNAB/2017_11-DB-import.csv', sep=';', index=False, columns=['Date', 'Payee', 'Memo', 'Inflow', 'Outflow'], decimal='.' )
Quick Extra Tip
If YNAB doesn't play nicely with np.nan, you can swap np.nan for "" in the np.where calls. Just note this will convert the columns to string type, but it should still work for import purposes. You can also verify your Betrag column is properly numerical by running print(df.dtypes)—if it shows object, add df['Betrag'] = pd.to_numeric(df['Betrag'], errors='coerce') right after reading the CSV to force conversion.
内容的提问来源于stack exchange,提问作者The1ne

