Lesser-known Pandas tricks (2019)
towardsdatascience.com
towardsdatascience.com
The other day I needed to scrape data from a table on a webpage. Thinking about traversing the DOM and building up an array was already giving me a headache. Thankfully pandas has the “read_html” function. Getting a list of dataframes for each table on the page was as easy as:
dfs = pd.read_html(url)pd.date_range(date_from, date_to, freq="D")
2. merge with indicator
if you set `indicator` parameter of merge() to True pandas adds a column that tells you which dataset the row came from
3. merge with approximate match - the tolerance parameter of merge_asof()
pd.merge_asof(trades, quotes, on="timestamp", by='ticker', tolerance=pd.Timedelta('10ms'), direction='backward')
4. Create an Excel report and add some charts
5. Save the dataframe in gzipped form
edit: formatting
edit2: I managed to get an outline link
Edit: not that it's a bad thing, I just mention it so people who read this know for sure they can avoid the link if they already know how to use the tips listed here. The article has code examples and more details.
EDIT: for instance, it looks like on a suitably configured environment, passing in `s3://` and `gs://` URLs works fine too...
left.merge(right, how="left", indicator=True, ...)
[lambda df: df._merge == "left_only"]The question was "How do I create a column where each row's value is the mean of another column's values starting at that row?" The answer was:
df.loc[::-1, 'col_1'].expanding().mean()[::-1]Separately, I find it upsetting there are at least 6 ways of reversing a dataframe. It suggests some API smell.
df[col].expanding(reverse=True).mean()
pd.period_range(date_from, date_to, freq = "D")
AFAICT, a PeriodIndex and DateTimeIndex function mostly the same, and have many of the same methods, except... * DateTimeIndex can't hold dates far in the future
* PeriodIndex can't easily round to the end of a period (e.g. date + 0*MonthEnd() errors)
* PeriodIndex doesn't handle timezones?5 lesser-known pandas tricks:
1. Date Ranges
2. Merge with indicator
3. Nearest merge by timestamp
4. Create an Excel report from pandas
5. Use gzip with when saving to csv