DEV Community

Suneel Kumar Kola
Suneel Kumar Kola

Posted on

Clean a messy Indian sales CSV for Power BI in 5 minutes with Python

Every month I get a sales export that looks fine in Excel and then falls apart the moment it hits pandas or Power BI. Amounts come through as "₹1,20,000". Customer IDs like 001 lose their leading zeros. Dates arrive as 15/01/2025, 2025-03-01, and 15-Jan-2025 in the same column. Cities show up as HYD, Hyd, Bangalore, and mumbai.

I got tired of fixing the same issues by hand, so I built EazyDataFix, an open-source Python library that applies a readable recipe and records every change. Here's how I take the sample Indian sales file from the repo and get Power BI-ready tables in a few minutes.

The messy file

The sample is examples/power_bi_ready/sales.csv. It has 11 rows, including a duplicate of order 1001, a padded city value, two unusable amounts (blank and n/a), and two dates that are not dd/mm/yyyy.

Order ID,Customer ID,City,Order Date,Amount,Channel
1001,001,HYD,15/01/2025,"₹1,250.50",Store
1001,001,HYD,15/01/2025,"₹1,250.50",Store
1002,002,Bangalore,02/02/2025,₹800,Online
1003,003, Hyd ,03/02/2025,"₹2,300",Store
1004,004,BLR,2025-03-01,₹450,Online
1005,005,Mumbai,15-Jan-2025,₹100,Store
1006,006,mumbai,16/01/2025,₹999.00,Online
1007,001,Hyderabad,20/01/2025,,Store
1008,007,Chennai,21/01/2025,n/a,Online
1009,008,DEL,22/01/2025,"₹12,000",Store
1010,009,New Delhi,23/01/2025,₹75.5,Online
Enter fullscreen mode Exit fullscreen mode

Save that as sales.csv, or pull the same file from the repo:

from pathlib import Path
import urllib.request

url = (
    "https://raw.githubusercontent.com/suneelprojects/eazydatafix"
    "/main/examples/power_bi_ready/sales.csv"
)
Path("sales.csv").write_bytes(urllib.request.urlopen(url, timeout=30).read())
Enter fullscreen mode Exit fullscreen mode

What goes wrong in plain pandas

import pandas as pd

df = pd.read_csv("sales.csv")
print(df[["Customer ID", "Amount", "Order Date", "City"]].head(3))
print(df[["Customer ID", "Amount", "Order Date"]].dtypes)
print(pd.to_numeric(df["Amount"], errors="coerce"))
Enter fullscreen mode Exit fullscreen mode

Customer ID is read as an integer, so 001 becomes 1. Amount stays text. pd.to_numeric(..., errors="coerce") turns every rupee value into NaN, including everyday Indian groupings like "₹1,20,000", "₹12,000", and "₹1,250.50".

Dates are worse if you let pandas guess:

print(pd.to_datetime(df["Order Date"], errors="coerce", format="mixed", dayfirst=True))
Enter fullscreen mode Exit fullscreen mode

Most dd/mm/yyyy values parse, but 2025-03-01 silently becomes 3 January 2025, not 1 March. I'd rather reject a date I didn't declare than load the wrong day into a dashboard.

City names stay messy too: HYD, Hyd, Bangalore, mumbai, and DEL would all show up as different places in a slicer.

A recipe instead of a pile of cleanup cells

pip install eazydatafix
Enter fullscreen mode Exit fullscreen mode

Spell out the rules in a recipe. IDs stay text, so leading zeros survive. Amounts drop the ₹ and the commas — the same treatment that turns "₹1,20,000" into a real number. Dates must match %d/%m/%Y; anything else is quarantined, not guessed. City aliases collapse to one spelling each. Chennai and Hyderabad already match the names I want, so they pass through. April is fiscal month 1, which is common for Indian reporting. There's no model deciding what to fix: the same file and the same recipe always produce the same tables and the same log.

import eazydatafix as edf

recipe = edf.PipelineRecipe(
    name="india_sales_powerbi",
    workflow="powerbi_ready",
    columns={
        "order_id": edf.ColumnRule(dtype="string"),
        "customer_id": edf.ColumnRule(dtype="string"),
        "city": edf.ColumnRule(
            dtype="string",
            category_mapping={
                "HYD": "Hyderabad",
                "Hyd": "Hyderabad",
                "BLR": "Bengaluru",
                "Bangalore": "Bengaluru",
                "mumbai": "Mumbai",
                "DEL": "New Delhi",
            },
        ),
        "order_date": edf.ColumnRule(
            dtype="datetime",
            date_format="%d/%m/%Y",
            on_error="quarantine",
        ),
        "amount": edf.ColumnRule(dtype="number", currency_symbols=("₹",)),
        "channel": edf.ColumnRule(dtype="string"),
    },
    powerbi_config=edf.PowerBIReadyConfig(
        table_name="sales",
        keys=(edf.PowerBIKey("sales", ("order_id",)),),
        generate_date_table=True,
        date_columns={"sales": ("order_date",)},
        fiscal_year_start_month=4,
    ),
)

pipeline = edf.Pipeline(recipe)
plan = pipeline.preview("sales.csv")
result = pipeline.apply("sales.csv", plan)

print(result.is_ready, result.readiness_result.readiness_score)
print(result.tables["sales"].to_string(index=False))
result.save("powerbi_output", formats=("csv", "excel"))
Enter fullscreen mode Exit fullscreen mode

preview does not change the source file. I apply only after the plan looks right. This run is ready, with a score of 100.0. You may see a pandas warning about day-first dates during a quality check; the recipe still parses with %d/%m/%Y.

The cleaned sales table keeps 001 as text, turns "₹12,000" into 12000.0, and leaves blank and n/a amounts as null on orders 1007 and 1008:

order_id customer_id      city order_date   amount channel
    1001         001 Hyderabad 2025-01-15   1250.5   Store
    1002         002 Bengaluru 2025-02-02    800.0  Online
    1003         003 Hyderabad 2025-02-03   2300.0   Store
    1006         006    Mumbai 2025-01-16    999.0  Online
    1007         001 Hyderabad 2025-01-20     <NA>   Store
    1008         007   Chennai 2025-01-21     <NA>  Online
    1009         008 New Delhi 2025-01-22  12000.0   Store
    1010         009 New Delhi 2025-01-23     75.5  Online
Enter fullscreen mode Exit fullscreen mode

The two rows whose dates didn't match the recipe are set aside, not forced into the model. Print them with result.rejected_rows["sales"]:

Order ID Customer ID   City  Order Date Amount Channel
    1004         004    BLR  2025-03-01   ₹450  Online
    1005         005 Mumbai 15-Jan-2025   ₹100   Store
Enter fullscreen mode Exit fullscreen mode

If the source format changes, I update date_format and preview again, rather than letting a second format slip in.

The change log

Every step is recorded, which is the part I want next to a dashboard:

for change in result.changes:
    print(
        f"{change.step}: rows {change.rows_before}->{change.rows_after}, "
        f"removed {change.removed_rows}, changed values {change.changed_values}"
    )
Enter fullscreen mode Exit fullscreen mode
clean/ColumnNormalizer: rows 11->11, removed 0, changed values 0
clean/WhitespaceTrimmer: rows 11->11, removed 0, changed values 1
clean/MissingMarkerDetector: rows 11->11, removed 0, changed values 2
column:amount: rows 11->11, removed 0, changed values 9
column:channel: rows 11->11, removed 0, changed values 0
column:city: rows 11->11, removed 0, changed values 7
column:customer_id: rows 11->11, removed 0, changed values 0
column:order_date: rows 11->9, removed 2, changed values 9
column:order_id: rows 9->9, removed 0, changed values 0
finish/DuplicateRemover: rows 9->8, removed 1, changed values 0
powerbi_ready: rows 20->20, removed 0, changed values 260
Enter fullscreen mode Exit fullscreen mode

Headings are normalised, " Hyd " is trimmed, blank and n/a amounts become null, nine currency values are parsed, seven city names are standardised, two dates are quarantined, and the duplicate order 1001 is removed. result.save(...) also writes pipeline_report.json with the same log.

The Power BI pass adds a continuous date table from 15 January 2025 through 3 February 2025: 20 days, one row per day. Because the fiscal year starts in April, 15 January 2025 is fiscal year 2025 and fiscal month 10.

Loading the files into Power BI

The output folder contains powerbi_ready_sales.csv (eight ready orders), powerbi_ready_date.csv, powerbi_ready.xlsx with both tables as sheets, powerbi_ready_readiness.json with field types, the score, and the relationship, sales_rejected.csv for orders 1004 and 1005, and a copy of the recipe.

In Power BI Desktop, use Get Data on the CSV files or the Excel workbook. Before you build visuals, check the types against the readiness file: IDs, city, and channel are Text, amount is Decimal Number, and order_date is Date. Relate sales.order_date to date.date as many-to-one. That relationship is already described in the JSON.

EazyDataFix prepares the model inputs. It does not create a .pbix file, visuals, measures, or a dashboard, and that's deliberate. I want the cleaning to be reviewable and repeatable. Save the recipe with recipe.save("india_sales_powerbi.json") and replay it next month with edf.Pipeline(edf.PipelineRecipe.load("india_sales_powerbi.json")).run("sales.csv").

If you'd rather start from a clone of the repo, the same flow is in python examples/power_bi_ready/prepare.py.

Try it

The quickstart notebook walks through a smaller sales file in Colab, with no local install. The code and this Power BI example are in the GitHub repo. Site and docs: eazydatafix.com.

pip install eazydatafix. If a recipe breaks on your export, I'd like to hear about it.

Top comments (0)