Reading CSVs in Python: pandas, polars, and datatable
Last updated: Dec 18, 2021
I typically use pandas
to read CSV files in Python. Anecdotally, most data scientists operating in the Python ecosystem do the same. When using R, I tend to bounce between dplyr
or data.table
. I always think about giving dtplyr a try to ge the “best of both worlds,” but I haven’t gotten around to it. I just came across the polars Python package today and thought I’d to a quick (and too simple) benchmark comparing pandas
, polars
(eager and lazy execution), and datatable
. This is by no means an exhaustive sample, and I have used others (e.g. csv
, dask
, siuba
) depending on the workflow and size.
import pandas as pd
import polars as pl
import datatable as dt
!wc -l /gpfs52/data/p_matheny_lab/khanms/data/imdb_folds.csv
50001 /gpfs52/data/p_matheny_lab/khanms/data/imdb_folds.csv
The file I use here is 50,000 lines containing mostly text (IMDb movie reviews). I’ll be using the %timeit
Jupyter magic command for time benchmarking here.
csv_file = '/gpfs52/data/p_matheny_lab/khanms/data/imdb_folds.csv'
pandas
%%timeit
pandas_df = pd.read_csv(csv_file)
404 ms ± 8.51 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
pd.read_csv(csv_file).head(3)
text | label | kfold | |
---|---|---|---|
0 | Meltdown opens on a scene of scientists prepar... | negative | 0 |
1 | Yes, I loved this movie when I was a kid. When... | positive | 0 |
2 | The precise text of an ad (except the word Chi... | positive | 0 |
polars
You can convert a polars
dataframe to a pandas
dataframe using polars_df.to_pandas()
.
%%timeit
# Eager execution
polars_df = pl.read_csv(csv_file)
84.2 ms ± 1.88 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
pl.read_csv(csv_file).head(3)
text | label | kfold |
---|---|---|
str | str | i64 |
"Meltdown opens on a scene of scientists preparing to conduct an important test on a missile system developed to deflect asteroids should they be on a collision course with earth. Nathan (Vincent Gale) mentions some misgivings to his, but the test appears to be an unqualified success. Then the asteroid breaks apart, and the largest piece is pushed into a direct collision path with earth. Fortunately, the huge rock skips off of earth's outer atmosphere and ricochets into space. Unfortunately, the glancing blow is just enough to alter earth's orbit, and the planet begins to spiral closer to the sun. While all of this is going on above their heads, Los Angeles cops Tom (Casper Van Dien) and Mick (Greg Anderson) are on a stake-out. They're supposed to collect evidence against a suspected drug dealer, but the deal they're watching quickly devolves into a shooting match. Afterward, Tom takes a few minutes to be interviewed by a local television reporter who also happens to be his girlfriend, Carly (Stefanie von Pfetten). At a nearby hospital where Mick is treated for a minor injury, Tom has a brief chat with his ex-girlfriend Bonnie (Venus Terzo), who is a nurse. He tells her he's concerned about the fact that their 17 year-old daughter Kimberly (Amanda Crew) is dating a man named CJ (Ryan McDonell). Once Tom explains to Bonnie that he's discovered CJ has a criminal record, she's a little worried herself. It's not long, however, before everybody has something else to worry about. The temperature is rapidly rising all around the world. Carly is one of the first non-scientists to learn what's really happening. Nathan, who is her brother, calls her to say he may have a way that they can survive. Carly calls Tom; he, of course, promptly contacts Bonnie. In relatively short order, the motley group is on the road. Before they can reach their ultimate goal, however, they've got to make their way through bands of looters, deal with a catastrophic water shortage, and manage to travel in temperatures that are high enough to kill. Casper Van Dien is a good looking guy, and I actually enjoyed him in Starship Troopers. That may be because he's good in action scenes. It might also be because he didn't talk much in that movie. In Meltdown, he's unfortunately given just enough lines in situations that are just dramatic enough to showcase his entirely average acting abilities. Amanda Crew is also okay, and Ryan McDonell isn't bad, either. Vincent Gale and Stefanie von Pfetten are also both reasonably good, but Venus Terzo is sadly on a par with Van Dien. What really makes or breaks a movie, though, is the story and the script. While the story here is okay and actually has some real potential, the script is just awful. The science part of the science fiction is non-existent starting with the asteroid pushing the earth out of orbit and escalating with the notion that the "gravitational balance of the solar system" might "pull the earth back" into its usual orbit "over time." When the temperature in LA hits 120 degrees, cars start blowing up. You know what's even worse than the bad science? The bad continuity. Okay, really hot. Why are people in the movie not only wearing long sleeved shirts, but jackets, too? Why are people mugging each other for bottled water instead of turning on the taps at home? Why are the streets completely empty, but the freeways completely full? And why are the freeways full of unexploded? It's almost superfluous to note that the sets, costumes, and production values were good, especially when that only forces me to say that the edits were not. So basically, you take a pretty good story idea and combine it with mostly mediocre acting, a terrible script, low-end special effects, utterly irrational plot twists, and poor edits, and what do you have? A movie that's even less than the sum of its inconsiderable parts. I'm sorry to say that I can't recommend Meltdown: Days of Destruction to anyone. POLITICAL NOTES: There is mention here that Congress finally loosened the purse strings enough to fund the tests that start the movie rolling. While the tests here were wholly irresponsible (targeting an asteroid with a nuke and not knowing the composition of the big rock is, in fact, well beyond irresponsible and approaching the insane), the fact is that such scenarios are a very real danger to the planet. Unfortunately, we've tracked nowhere near all of the near earth asteroids that could be worrisome in some orbit some day; and our ability to spot something on a collision course with us is limited at best. Once we do discover we're going to be hit, we quite literally have no system in place to deal with it. There are no nuclear-tipped space missiles we can launch; the space shuttle is completely incapable of going beyond earth orbit, and if it were, we couldn't launch enough of them or launch them quickly enough for it to matter. I'm not big on the government doing anything beyond its constitutional mandates, but I certainly think protecting the planet from destruction coming at us from outer space could be construed as defending the country, don't you? FAMILY SUITABILITY: Meltdown: Days of Destruction is rated R for "some violence." I frankly didn't find the violence here anything beyond a fairly typical T-rated video game. If your teens are keen on seeing Meltdown and you can't talk them out of it, the R-rating shouldn't dissuade you from letting them see it. It's not, however, a good idea to leave the younger kids in the room with their elder siblings. While the shootings aren't too graphic in the main, some of the dead bodies are." |
"negative" | 0 |
"Yes, I loved this movie when I was a kid. When I was growing up I saw this movie so many times that my dad had to buy another VHS copy because the old copy had worn out. My family received a VHS copy of this movie when we purchased a new VHS system. At first, my mom wasn't sure that this was an appropriate movie for a 10 year old but because we had just bought a new VHS system she let me watch it. Like I said, this movie is every little boys dream The movie contains a terrific setting, big muscled barbarians, beautiful topless women, big bad monsters and jokes you'll only get when you get older. So, a couple of days ago I inserted the video and watched the movie again after a long time. At first, I was bored, then started thinking about how much I loved this movie when I was kid, and continued watching. Yeah, the experience wasn't as great as I remembered The acting is pretty bad, the storyline is pretty bad, the jokes weren't funny anymore, but the women were still pretty. Yes, I've grown up. Even though the movie experience has changed for me, I still think it's worth 7 stars. For the good old times you know " |
"positive" | 0 |
"The precise text of an ad (except the word Chinese, as in Grauman's Chinese, at the end, should appear in caps but IMDb's racially sensitive formatting won't let it), as published in the Los Angeles Times of October 2nd 1930, reads as follows (with " / " denoting the break between each line in the ad): GALA WORLD PREMIERE / Tonight / 8:30 PROMPTLY / TONIGHT all Hollywood and Los Angeles boulevards become THE BIG TRAIL to Grauman's Chinese Theatre...the rendezvous of all that is beautiful and brilliant...the gathering place of stars...celebrities...the great and the famous! Thousands will fill every seat...many thousands will line Hollywood Boulevard to watch the gala festivities attending this world premiere! Tonight all Southern California pays homage to the great American Epic, which faithfully depicts the thrilling, soul-stirring romance of the American Pioneers..who won the West and left us a heritage of Peace..Liberty..and Happiness. Raoul Walsh's / The BIG / TRAIL / Story by HAL G. EVARTS / FOX MOVIETONE PRODUCTION / SHOWN ENTIRELY IN / GRANDEUR / Cast of 20,000 featuring / JOHN WAYNE MARGUERITE CHURCHILL / EL BRENDEL / Tully Marshall Tyrone Power / David Rollins / Frederick Burton, Charles Stevens, Russ Powell, Louise Carter / William V. Mong, Dodo Newton, Ward Bond, Marcia Harris / Marjorie Leet, Emelie Emerson, Fran Rainboth / Andy Shufford, Helen Parrish / Production Manager Archibald Buchanan / Settings by Harold Miles, Fred Serren / Chief Grandeur Cameraman Arthur Edeson / Sound Engineer George Leverett / Chief Film Cutter Jack Dennis / ADDED FEATURE: / Fox Movietone News Exclusive Interview with / GEORGE BERNARD SHAW / Direction Carli Elinor / GRAUMAN'S / Chinese / Direction of Fox West Coast Theatres / Twice Daily Thereafter / 2:30 --- 8:30 P.M." |
"positive" | 0 |
%%timeit
# Lazy execution
polars_df_lazy = pl.scan_csv(csv_file)
765 µs ± 39.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
pl.scan_csv(csv_file).head(3)
<polars.internals.lazy_frame.LazyFrame at 0x7f36b2154be0>
# Use `collect` method
pl.scan_csv(csv_file).head(3).collect()
text | label | kfold |
---|---|---|
str | str | i64 |
"Meltdown opens on a scene of scientists preparing to conduct an important test on a missile system developed to deflect asteroids should they be on a collision course with earth. Nathan (Vincent Gale) mentions some misgivings to his, but the test appears to be an unqualified success. Then the asteroid breaks apart, and the largest piece is pushed into a direct collision path with earth. Fortunately, the huge rock skips off of earth's outer atmosphere and ricochets into space. Unfortunately, the glancing blow is just enough to alter earth's orbit, and the planet begins to spiral closer to the sun. While all of this is going on above their heads, Los Angeles cops Tom (Casper Van Dien) and Mick (Greg Anderson) are on a stake-out. They're supposed to collect evidence against a suspected drug dealer, but the deal they're watching quickly devolves into a shooting match. Afterward, Tom takes a few minutes to be interviewed by a local television reporter who also happens to be his girlfriend, Carly (Stefanie von Pfetten). At a nearby hospital where Mick is treated for a minor injury, Tom has a brief chat with his ex-girlfriend Bonnie (Venus Terzo), who is a nurse. He tells her he's concerned about the fact that their 17 year-old daughter Kimberly (Amanda Crew) is dating a man named CJ (Ryan McDonell). Once Tom explains to Bonnie that he's discovered CJ has a criminal record, she's a little worried herself. It's not long, however, before everybody has something else to worry about. The temperature is rapidly rising all around the world. Carly is one of the first non-scientists to learn what's really happening. Nathan, who is her brother, calls her to say he may have a way that they can survive. Carly calls Tom; he, of course, promptly contacts Bonnie. In relatively short order, the motley group is on the road. Before they can reach their ultimate goal, however, they've got to make their way through bands of looters, deal with a catastrophic water shortage, and manage to travel in temperatures that are high enough to kill. Casper Van Dien is a good looking guy, and I actually enjoyed him in Starship Troopers. That may be because he's good in action scenes. It might also be because he didn't talk much in that movie. In Meltdown, he's unfortunately given just enough lines in situations that are just dramatic enough to showcase his entirely average acting abilities. Amanda Crew is also okay, and Ryan McDonell isn't bad, either. Vincent Gale and Stefanie von Pfetten are also both reasonably good, but Venus Terzo is sadly on a par with Van Dien. What really makes or breaks a movie, though, is the story and the script. While the story here is okay and actually has some real potential, the script is just awful. The science part of the science fiction is non-existent starting with the asteroid pushing the earth out of orbit and escalating with the notion that the "gravitational balance of the solar system" might "pull the earth back" into its usual orbit "over time." When the temperature in LA hits 120 degrees, cars start blowing up. You know what's even worse than the bad science? The bad continuity. Okay, really hot. Why are people in the movie not only wearing long sleeved shirts, but jackets, too? Why are people mugging each other for bottled water instead of turning on the taps at home? Why are the streets completely empty, but the freeways completely full? And why are the freeways full of unexploded? It's almost superfluous to note that the sets, costumes, and production values were good, especially when that only forces me to say that the edits were not. So basically, you take a pretty good story idea and combine it with mostly mediocre acting, a terrible script, low-end special effects, utterly irrational plot twists, and poor edits, and what do you have? A movie that's even less than the sum of its inconsiderable parts. I'm sorry to say that I can't recommend Meltdown: Days of Destruction to anyone. POLITICAL NOTES: There is mention here that Congress finally loosened the purse strings enough to fund the tests that start the movie rolling. While the tests here were wholly irresponsible (targeting an asteroid with a nuke and not knowing the composition of the big rock is, in fact, well beyond irresponsible and approaching the insane), the fact is that such scenarios are a very real danger to the planet. Unfortunately, we've tracked nowhere near all of the near earth asteroids that could be worrisome in some orbit some day; and our ability to spot something on a collision course with us is limited at best. Once we do discover we're going to be hit, we quite literally have no system in place to deal with it. There are no nuclear-tipped space missiles we can launch; the space shuttle is completely incapable of going beyond earth orbit, and if it were, we couldn't launch enough of them or launch them quickly enough for it to matter. I'm not big on the government doing anything beyond its constitutional mandates, but I certainly think protecting the planet from destruction coming at us from outer space could be construed as defending the country, don't you? FAMILY SUITABILITY: Meltdown: Days of Destruction is rated R for "some violence." I frankly didn't find the violence here anything beyond a fairly typical T-rated video game. If your teens are keen on seeing Meltdown and you can't talk them out of it, the R-rating shouldn't dissuade you from letting them see it. It's not, however, a good idea to leave the younger kids in the room with their elder siblings. While the shootings aren't too graphic in the main, some of the dead bodies are." |
"negative" | 0 |
"Yes, I loved this movie when I was a kid. When I was growing up I saw this movie so many times that my dad had to buy another VHS copy because the old copy had worn out. My family received a VHS copy of this movie when we purchased a new VHS system. At first, my mom wasn't sure that this was an appropriate movie for a 10 year old but because we had just bought a new VHS system she let me watch it. Like I said, this movie is every little boys dream The movie contains a terrific setting, big muscled barbarians, beautiful topless women, big bad monsters and jokes you'll only get when you get older. So, a couple of days ago I inserted the video and watched the movie again after a long time. At first, I was bored, then started thinking about how much I loved this movie when I was kid, and continued watching. Yeah, the experience wasn't as great as I remembered The acting is pretty bad, the storyline is pretty bad, the jokes weren't funny anymore, but the women were still pretty. Yes, I've grown up. Even though the movie experience has changed for me, I still think it's worth 7 stars. For the good old times you know " |
"positive" | 0 |
"The precise text of an ad (except the word Chinese, as in Grauman's Chinese, at the end, should appear in caps but IMDb's racially sensitive formatting won't let it), as published in the Los Angeles Times of October 2nd 1930, reads as follows (with " / " denoting the break between each line in the ad): GALA WORLD PREMIERE / Tonight / 8:30 PROMPTLY / TONIGHT all Hollywood and Los Angeles boulevards become THE BIG TRAIL to Grauman's Chinese Theatre...the rendezvous of all that is beautiful and brilliant...the gathering place of stars...celebrities...the great and the famous! Thousands will fill every seat...many thousands will line Hollywood Boulevard to watch the gala festivities attending this world premiere! Tonight all Southern California pays homage to the great American Epic, which faithfully depicts the thrilling, soul-stirring romance of the American Pioneers..who won the West and left us a heritage of Peace..Liberty..and Happiness. Raoul Walsh's / The BIG / TRAIL / Story by HAL G. EVARTS / FOX MOVIETONE PRODUCTION / SHOWN ENTIRELY IN / GRANDEUR / Cast of 20,000 featuring / JOHN WAYNE MARGUERITE CHURCHILL / EL BRENDEL / Tully Marshall Tyrone Power / David Rollins / Frederick Burton, Charles Stevens, Russ Powell, Louise Carter / William V. Mong, Dodo Newton, Ward Bond, Marcia Harris / Marjorie Leet, Emelie Emerson, Fran Rainboth / Andy Shufford, Helen Parrish / Production Manager Archibald Buchanan / Settings by Harold Miles, Fred Serren / Chief Grandeur Cameraman Arthur Edeson / Sound Engineer George Leverett / Chief Film Cutter Jack Dennis / ADDED FEATURE: / Fox Movietone News Exclusive Interview with / GEORGE BERNARD SHAW / Direction Carli Elinor / GRAUMAN'S / Chinese / Direction of Fox West Coast Theatres / Twice Daily Thereafter / 2:30 --- 8:30 P.M." |
"positive" | 0 |
datatable
You can convert a datatable
dataframe to a pandas
dataframe using datatable_df.to_pandas()
.
%%timeit
datatable_df = dt.fread(csv_file)
161 ms ± 15.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
dt.fread(csv_file).head(3)
text | label | kfold | |
---|---|---|---|
▪▪▪▪ | ▪▪▪▪ | ▪▪▪▪ | |
0 | Meltdown opens on a scene of scientists preparing | negative | 0 |
1 | Yes, I loved this movie when I was a kid. When I w | positive | 0 |
2 | The precise text of an ad (except the word Chinese | positive | 0 |