Python/Pandas question and comparing dataframes

Pocky Is God

Ars Legatus Legionis
24,457
I have an excel sheet that I want to compare old and new prices with.

I know I can use the df.compare to get the difference between the old and new prices like this:

Code:
 df1['price_diference'] = np.where(df1['old_price'] == df2['new_price'], 0, df1['old_price'] - df2['new_price'])

But what I'm curious about is if I have ~47K lines to go through, but my list of new prices is only, say, 7-8 rows long. Will pandas iterate through the entirety of the column of 47K lines if I assign that as df1 and have it compare to the new price that is only 8 rows deep? Or do I have to do a for loop somewhere to make sure I compare every line in df1 against the new prices?
 

Pocky Is God

Ars Legatus Legionis
24,457
Lets see if I can give you a visual:




So The claim numbers and already paid amounts are 47000 lines of CPT codes and allowed/paid amounts. My list of CPT codes and their new prices are only 7-8 codes and their new prices.

I need to determine the difference between what was already paid in the total payment column against the CPT code and new price we should have paid for each of the matching codes.

So ideally, I would have pandas look at the cpt code, match 90887 to 90887 and subtract the new price, from the already paid price to determine the difference.
 

Pocky Is God

Ars Legatus Legionis
24,457
That should be easy to whip up. Question.

and subtract the new price, from the already paid price to determine the difference.

So in your picture, both new prices are higher, so you'd expect the result to be "-15.5" and "-5"?

Sorry, misspoke, new price minus already paid, to get the net difference I/we owe this provider. So if we paid 115, but the new price is 120, I'd get a new column DIFFERENCE with the the +5 owed to the provider.
 

sryan2k1

Ars Legatus Legionis
46,877
Subscriptor++
I know you said python/pandas but I'm a powershell guy so here's what I cranked out.

Have a CSV with the following columns (and data, obviously):
Code:
"Claim Number","CPT Code","Total allowed","Total Payment","New Price"

Edit: Actually the only columns the script cares about are CPT Code and New Price, adjust the code accordingly if you want them named something else.

Edit the top of this script for all the CPT's you have with new values (the quotes around them are important even though they're just numbers)

Code:
$updated_CPT = @{
"11111" = "100.50"
"22222" = "200"
}

$claims = Import-Csv .\CPT.csv


foreach ($claim in $claims)
{
    if ($updated_CPT.Contains($claim.'CPT Code'))
    {
        $claim.'New Price' = $updated_CPT[$claim.'CPT Code'] - $claim.'Total Payment'
    }
} 


$claims | Export-Csv -Force -NoTypeInformation .\CPT.csv #Change this if you don't want to overwrite the original


That will update "CPT.csv" in the same directory you're working in with the adjusted values.


Modify as necessary.
 

Pocky Is God

Ars Legatus Legionis
24,457
Thanks everyone.

Was getting weird hash errors with the Power Shell script, so I gave it some elbow grease and got it going with this nugget:

Code:
import pandas as pd
import numpy as np

def get_data_from_excel(path_to_filename, sheet_name):
    dataframe1 = pd.read_excel(
        io=path_to_filename,
        engine="openpyxl",
        sheet_name=sheet_name,
        # skiprows=3,
        #usecols="A:BU",
        ##nrows=921000,
    )

    return dataframe1


df1 = get_data_from_excel("ES_CODES_CGV_EDIT.xlsx", "Sheet1" )
##df2 = get_data_from_excel("ES_Settlement_10.18_EDITS.xlsx")
##final = df1.merge(df2,  how='left' , left_on = 'LINE' , right_on= 'QUANTITY')
##total_allowed = df1['LINE_TOTAL_ALLOWED']

df2 = df1.drop_duplicates(keep = 'first')





##df1['COST_PER_UNIT'] = np.where(df1['PROC_CODE'] =="97153, 97154, 97155, 90885, 97156, 97530, 97535", (df1['LINE_TOTAL_ALLOWED'])/15, "Not paid per Unit" )

##df1['COST_PER_UNIT'] = np.where(df1['PROC_CODE'].isin([97153, 97154, 97155, 90885, 97156, 97530, 97535]), df1['LINE_TOTAL_ALLOWED']/15 )



with pd.ExcelWriter("ES_CODES_CGV_EDIT.xlsx") as writer:
    ##df1.to_excel(writer, sheet_name="Sheet1")
   df2.to_excel(writer, sheet_name="Sheet2")
    ##final.to_excel(writer, sheet_name="Sheet3")

print(df2)

This worked, and lined up all of the codes associated with their per unit pricing correctly. Step 1 completed. Now, to get a per unit price, I thought this would do it using numpy and np.where:

Code:
df1['COST_PER_UNIT'] = np.where(df1['PROC_CODE'] =="97153, 97154, 97155, 90885, 97156, 97530, 97535", (df1['LINE_TOTAL_ALLOWED'])/15, "Not paid per Unit" )

However, I'm not sure if the I cannot use a function to get the per unit price, since the procedure codes listed above are billed in 15 minute increments, but I get no errors, but I just get every line in the column COST_PER_UNIT to state "Not paid per unit". Which is obviously not correct.

Any ideas?
 

QuadDamaged

Ars Praefectus
3,983
Subscriptor++
Pandas is dreadfully slow when it comes down to:
1/ IO
2/ Memory Allocation

Most pandas operations are super wasteful when it comes to memory use. There's been a push recently to build JIT-ed versions of pandas the pandas operations create a set of transforms (like an SQL statement) that is then optimized by the runtime when the results are observed.

My favorite so far is Polars (successor to weld.rs / grizzly)
 
Pandas is dreadfully slow when it comes down to:
1/ IO
2/ Memory Allocation

Most pandas operations are super wasteful when it comes to memory use. There's been a push recently to build JIT-ed versions of pandas the pandas operations create a set of transforms (like an SQL statement) that is then optimized by the runtime when the results are observed.

My favorite so far is Polars (successor to weld.rs / grizzly)

Thank you for this. As I'm writing more and more rust I would have loved this challenge to be written there. For my scripts I was waiting 20+ minutes for it to complete.

I had attempted a df1(np.where...) operation with two rather large files and got an interesting numpy error/timeout that it couldn't allocate the 1.11TB of memory the action had requested/needed. I thought that was fun.
 
Can we talk about this bit of code for my own peace of mind?

Code:
df1['COST_PER_UNIT'] = np.where(df1['PROC_CODE'] =="97153, 97154, 97155, 90885, 97156, 97530, 97535", (df1['LINE_TOTAL_ALLOWED'])/15, "Not paid per Unit" )


Basically, prototyping it out: I wanted the script to look in the column holding the above CPT Codes ["97153, 97154, 97155, 90885, 97156, 97530, 97535"], and if there was a match in CPT code, to then look into the the ['LINE_TOTAL_ALLOWED'] and take that amount, divided by 15, and drop that result off into ['COST_PER_UNIT'] column, if there was not a match, put in "Not Paid per Unit".

I wasn't able to get that to work, was my syntax correct or not correct?
 

QuadDamaged

Ars Praefectus
3,983
Subscriptor++
Can we talk about this bit of code for my own peace of mind?

Code:
df1['COST_PER_UNIT'] = np.where(df1['PROC_CODE'] =="97153, 97154, 97155, 90885, 97156, 97530, 97535", (df1['LINE_TOTAL_ALLOWED'])/15, "Not paid per Unit" )


Basically, prototyping it out: I wanted the script to look in the column holding the above CPT Codes ["97153, 97154, 97155, 90885, 97156, 97530, 97535"], and if there was a match in CPT code, to then look into the the ['LINE_TOTAL_ALLOWED'] and take that amount, divided by 15, and drop that result off into ['COST_PER_UNIT'] column, if there was not a match, put in "Not Paid per Unit".

I wasn't able to get that to work, was my syntax correct or not correct?

Let's work this pandas BS out step by step.

Code:
import pandas as pd
import numpy as np

# load the data, and index it by PROC_CODE
df=pd.DataFrame({"PROC_CODE":["foo","bar","baz","nice"],"LINE_TOTAL_ALLOWED":[42,666,np.NaN,69]})
df=df.set_index("PROC_CODE")
print("🐼 loaded dataframe with index")
print(df)

# list the product keys we want to compute for
product_codes = ["foo","bar"]
print("🐼 product codes")
print(product_codes)

#use Panda's multindexer / type magic / total BS to perform the lookup of prices
to_add=df.loc[product_codes]["LINE_TOTAL_ALLOWED"]/15
print(f"🐼 prices for {product_codes}")
print(to_add)

# concatenate the partial (INDEXED) to_add dataframe in a new series (1d column)
df["COST_PER_UNIT"]=to_add # pandas (Magic | BS)  in action
print("🐼 merged dataframes with partial prices")
print(df)

# replace COST_PER_UNIT NaN with 'Not Paid Per Unit
df["COST_PER_UNIT"]=df["COST_PER_UNIT"].fillna('Not Paid per Unit')
print("🐼 stringified COST_PER_UNIT column means math ops will be _slow_ now")
print(df)

Which prints
Code:
🐼 loaded dataframe with index
           LINE_TOTAL_ALLOWED
PROC_CODE                    
foo                      42.0
bar                     666.0
baz                       NaN
nice                     69.0
🐼 product codes
['foo', 'bar']
🐼 prices for ['foo', 'bar']
PROC_CODE
foo     2.8
bar    44.4
Name: LINE_TOTAL_ALLOWED, dtype: float64
🐼 merged dataframes with partial prices
           LINE_TOTAL_ALLOWED  COST_PER_UNIT
PROC_CODE                                   
foo                      42.0            2.8
bar                     666.0           44.4
baz                       NaN            NaN
nice                     69.0            NaN
🐼 stringified COST_PER_UNIT column means math ops will be _slow_ now
           LINE_TOTAL_ALLOWED      COST_PER_UNIT
PROC_CODE                                       
foo                      42.0                2.8
bar                     666.0               44.4
baz                       NaN  Not Paid per Unit
nice                     69.0  Not Paid per Unit

Why do I hate this mode of programming? Because I have to recall too many details and keep these in my head whilst coding, and there's only space for 9 things at a time on my 1970s-era processing unit.

Give me type safety or give me death!
 

QuadDamaged

Ars Praefectus
3,983
Subscriptor++
* note that if you have multiple columns for you Primary Key you can use a multiindex
Code:
df.set_index(['ANOTHER_COL','PROC_CODE','YET_ANOTHER_COL'])
# and lookup on ranges
df.loc[:,product_codes,:]

the range':' means anything I think. You may have to use .iloc(...), I can't remember all this without running in the REPL

Thinking about why I want type safety, it's because with IDEs you can explore a lot of the API surface before runtime, and a properly-designed typesystem will go much further than a vastly-documented API. Pandas has extensive documentation, but it's nearly impossible to discover it via its typesystem (even using mypy), making it extremely confusing for old farts like me that have been using more intuitive tools since the late 90s, even if it's in C++.

Now I can't even keep track of the number of allocations here. Polars will turn the whole thing (get rid of the prints) into a big query and do operations in-place, run optimisers, pre-allocate as needed. Pandas 🐼 being immediate vs Polars 🐻‍❄️ being lazy makes all the difference here in terms of performance.
 
I appreciate the readability of Python more than when I started learning it last year, but yeah I agree, there's a lot of documentation but the type hints are non-existent, and if you are not using a Jupyter notebook, you have to pray that what you wrote will actually run. Its a very good language for prototyping shit out, but man, it runs slow as fuck and can be infuriating like you said.

I can't imagine using python for using anything other than scripts. Yet, I see people attempting to write games in it. Ew.
 
D

Deleted member 43669

Guest
Yes, even the Python maintainers have been betting heavily on type hints (and yes, IDE-ability might be even more important than safety). And while I think this is something that doesn't work as well when added late in the game, Python still has lots going for it.

The usual Python advocacy of "dev speed trumps runtime speed" and "just use C [or Rust, pyo3 looks awesome] for the little bits that matter" are fairly spot-on in most cases. No language can do it all, but Python is one of the languages I reach out for more often.

and if you are not using a Jupyter notebook, you have to pray that what you wrote will actually run.

I'm intrigued by this, because Jupyter notebooks IMHO are notoriously error-prone. Reactive notebooks seem like they address most of what concerns me, but I haven't really used those yet.
 
We support customers processing terabytes, if not more, of data with it.

Let’s just say we don’t tell our customers how to do their jobs, we just support their hardware needs. :judge: (hence why I oranged for curiosity, since I have less visibility into this side of things than I’d like!)

Don't tell my boss but I moved the spreadsheets I was working with to my home desktop (5800X, 64GB of RAM) to do the heavy lifting. And it still took 15+ minutes of processing time to manipulate my 500MB files. I can't imagine Terabytes of data being run through what I consider to be fairly easy/innocuous code I wrote up.
 

sryan2k1

Ars Legatus Legionis
46,877
Subscriptor++
At that level you should stop trying to half ass it with scripting and write an actual .NET (or whatever) app to do it.


It should take single digit seconds to do what you want. Alternatively, load it into a database and use SQL or stored procedures to manipulate what you want.


At 500MB files you're basically asking a horse to fix a radiator. He's gonna do his best but will end up frustrated.


I'm still very curious what errors you were seeing on the powershell. That should be reasonably performant without actually getting to compiled code.
 
D

Deleted member 43669

Guest
I was a bit curious about this (in the past, colleagues have reached for Pandas when dealing with tabular data... when I thought it was overkill and caused inconveniences).

Yes, it just uses RAM, and memory size balloons to about 2x of the disk size of the sample CSV files I tried; and of course when I tried to operate on a >4gb CSV file on my 8gb laptop I was visited by the OOM killer. But after trimming the file to 569mb, Pandas seemed quite responsive. Running functions like df.max(), which should scan the whole table, was instantaneous.

Pandas uses numpy, which is a lot of C, so many Pandas operations should run at nearly-C speeds. I created a derived table with apply and a lambda, using random.randrange- which was complex enough to not be optimized away, and it took my (old) laptop about 4m to run.

That seems to be much more efficient than naïve Python- using csv.reader ballooned mem usage so much it was not bearable.

So... for that kind of datasets, as long as you are able to do everything with Pandas built-in functions, it should be good (even for much larger datasets, I imagine; as much as half your RAM, I guess). However, falling back to processing that under Python will be *slow*.

I really doubt any other interpreted language is going to differ in an order of magnitude from Python.

Any compiled language is probably going to work as well as, or better than Pandas (using native operations)- it will be fast if your dataset fits in RAM (unless you have a really ungodly amount of RAM). But in most ways of working, as soon as you hit swap, it will be back to waiting.

Then it's about using stuff which handles bigger-than-RAM datasets well. Such as a database.

I cat'ed the 4gb CSV twice, to get a CSV larger than my RAM, and imported that into an SQLite database. That took about 5-6 minutes, but then full table scans took about 30s, which is reasonable- but after creating an index (that took looong- and while SQLite was sipping RAM prior to this, it also took RAM), it was instantaneous.

...

Conclusion: Pandas will be good for datasets about half your RAM, as long as you don't fall into processing stuff into Python- but supposedly the point of Pandas/numpy is that you can avoid Python in most circumstances. Compiled languages will probably work better, and not require you to carefully craft your code to use native compiled functions- because your code will already be native compiled functions. But then you will also hit problems when your dataset starts to be too big for your RAM. Then something disk-aware will be the way to go.

I was surprised myself- I expected Python to be inefficient, but not "4-minutes slow" when processing a 500mb CSV. I was wrong by an order of magnitude (I'd expect a compiled language to deal with that file instantly, interpreted dynamic language to handle it in less than a minute). This is good to play around for a while- because my advice generally is "don't really worry too much if your dataset fits in RAM". A couple hundred of megabytes makes it worthwhile to worry a little bit :)
 
Your two options for working with dataframes is Python and R, and I know which of the two I'd pick. The alternatives to the dataframes paradigm is SQL, and then the comments about runtime speed mattering way less than developer time are spot on. Any particular bottlenecks in performance can be improved with IronPython, or any similar hook to compiled languages.

I started in data science and then moved to data engineering. Data scientists love Python for good reason. It's infinitely friendlier to work with than R, and any possible support library you would need has already been written by the community. This definitely trumps faster run time.

On Friday, I had an urgent request to create an alert when there were spikes in GitHub pulls. This was a piece of cake to write as a Python Cloud Function becauase find_peaks() is already a function in SciPy's suite of signal processing tools. I didn't need to write my own statistical functions to do this, I already have a tested and peer reviewed library that does it, all I have to do is feed it my data.

My team ingests several TB of data a day. We don't need to process every last bit by a single script in an interpreted language, and that's how we are able to process it all in time. It's about architecting the system so it can process the workload in parallel chunks. Dev time is dramatically shorter than any alternative language, and that's the real cost. Compute time is dirt cheap on GCP in comparison. At the end of the day, everything ends up as a background job so it's not like youre sitting interactively at the console waiting for your results.
 
Last edited:
  • Like
Reactions: continuum
At that level you should stop trying to half ass it with scripting and write an actual .NET (or whatever) app to do it.


It should take single digit seconds to do what you want. Alternatively, load it into a database and use SQL or stored procedures to manipulate what you want.


At 500MB files you're basically asking a horse to fix a radiator. He's gonna do his best but will end up frustrated.


I'm still very curious what errors you were seeing on the powershell. That should be reasonably performant without actually getting to compiled code.
Do you work with any data ingestion pipelines? Nobody does this with .NET. If it's not Python, something that runs in the JVM is used such as Java or Scala. I don't know of any serious data engineering tools written for .NET. You have PowerBI, but that's data analysis, not engineering.

And you never use SQL and stored procedures to do transformation. That way madness lies. SQL is barely a procedural language, even with stored procedures bolted on top.
 
Last edited:
Also, is this the life of a data person? Cleaning up shitty excel data to try and make sense of this shit.

Working with 500+MB files is slow as all hell, even with Python/Pandas/Numpy.
Data cleaning is just step 1 of exploratory data analysis.

Data engineers don't do EDA, but data scientists do. Data engineers build the pipelines that ingest the raw data and give a usable dataset for the data scientists to explore. Data analysts can use either that, or the output of data scientists to build visual representations (and other modes) of the insights that data scientists gather (plus derive their own insights), often for an audience of members of other departments such as sales, marketing, finance, etc.
 
Not directly, but there are a large number of .NET only shops out there. Just because the industry prefers something else doesn't mean it doesn't exist.
I'm sure it exists, there are probably companies out there doing ETL using COBOL too. But I wouldn't recommend to someone "At that level you should stop trying to half ass it with scripting and write an actual COBOL (or whatever) app to do it."

ETL and ELT are not done exclusively in Python, by any means, in fact, it's only gaining ground now. It's still largely done with JVM languages.
 

fitten

Ars Legatus Legionis
55,632
Subscriptor++
Do you work with any data ingestion pipelines? Nobody does this with .NET. If it's not Python, something that runs in the JVM is used such as Java or Scala. I don't know of any serious data engineering tools written for .NET. You have PowerBI, but that's data analysis, not engineering.

And you never use SQL and stored procedures to do transformation. That way madness lies. SQL is barely a procedural language, even with stored procedures bolted on top.

We wrote an entire ETL system on top of SQL, the engine entirely in stored procedures (web based UI). The target was fixed but the sources weren't. That was ~15 years ago. Just last year I worked on an ETL system (in no way related to that other one a long time ago) that did the initial staging of data using Python (got data from dumps and put into the staging database) and all the transformations were done in SQL stored procedures.
 

continuum

Ars Legatus Legionis
98,320
Moderator
Data scientists love Python for good reason. It's infinitely friendlier to work with than R, and any possible support library you would need has already been written by the community. This definitely trumps faster run time.
So much this in my experience. I was just at a data science conference and sat in on multiple Julia, Python, R, etc. community talks... and while you can wax lyrical about advantages in one language or another, the specific field you're in and whatever language dominates -- and hence the support you get from the community-- is usually an extremely convincing reason to stick with the dominate programming language.
 
For data comparison, I really like the package DataComPy. You get these awesome reports when comparing dataframes very easily:

Code:
DataFrame Summary
-----------------

  DataFrame  Columns  Rows
0  original        5     6
1       new        4     5

Column Summary
--------------

Number of columns in common: 4
Number of columns in original but not in new: 1
Number of columns in new but not in original: 0

Row Summary
-----------

Matched on: acct_id
Any duplicates on match values: Yes
Absolute Tolerance: 0.0001
Relative Tolerance: 0
Number of rows in common: 5
Number of rows in original but not in new: 1
Number of rows in new but not in original: 0

Number of rows with some compared columns unequal: 5
Number of rows with all compared columns equal: 0

Column Comparison
-----------------

Number of columns compared with some values unequal: 3
Number of columns compared with all values equal: 1
Total number of values which compare unequal: 7

Columns with Unequal Values or Types
------------------------------------

       Column original dtype new dtype  # Unequal  Max Diff  # Null Diff
0  dollar_amt        float64   float64          1    0.0500            0
1   float_fld        float64   float64          4    0.0005            3
2        name         object    object          2    0.0000            0

Sample Rows with Unequal Values
-------------------------------

       acct_id  dollar_amt (original)  dollar_amt (new)
0  10000001234                 123.45             123.4

       acct_id  float_fld (original)  float_fld (new)
0  10000001234            14530.1555        14530.155
5  10000001238                   NaN          111.000
2  10000001236                   NaN            1.000
1  10000001235                1.0000              NaN

       acct_id name (original)            name (new)
0  10000001234  George Maharis  George Michael Bluth
3  10000001237      Bob Loblaw         Robert Loblaw

Sample Rows Only in original (First 10 Columns)
-----------------------------------------------

       acct_id  dollar_amt           name  float_fld    date_fld
4  10000001238        1.05  Lucille Bluth        NaN  2017-01-01

As far as folks talking about speed. I've become very partial to DuckDB recently. It's incredibly fast compared to pandas.

I'll usually use it to do bulk operations on data, then do the final bits of manipulation inside pandas.

Also, Pandas 2.0 is coming out soon, which will have the new (opt-in) Arrow backend. This should significantly improve speed and memory efficiency. Alternatively, there are other dataframe libraries like Polars and Vaex which are already based on Arrow.