Last active
August 29, 2015 14:15
-
-
Save ramhiser/61e60b0a7b21422edee8 to your computer and use it in GitHub Desktop.
Reindexing Pandas DataFrame with MultiIindex.from_product triggers missing values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
df = pd.DataFrame([['01-02-2015', 'a', 17], | |
['01-09-2015', 'a', 42], | |
['01-30-2015', 'a', 19], | |
['01-02-2015', 'b', 23], | |
['01-23-2015', 'b', 1], | |
['01-30-2015', 'b', 13]]) | |
df.columns = ['date', 'group', 'response'] | |
df.set_index(['date', 'group'], inplace=True) | |
#date_idx = pd.date_range('01-02-2015', '01-30-2015', freq='7D') | |
date_idx = ['01-02-2015', '01-09-2015', '01-16-2015', '01-23-2015', '01-30-2015'] | |
group_idx = ['a', 'b'] | |
idx_product = pd.MultiIndex.from_product([date_idx, group_idx], names=['date', 'group']) | |
df.reindex(idx_product, fill_value=0) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Pandas 0.15.2 | |
import pandas as pd | |
# Goal: Fill missing date/group pairs with response = 0 using Cartesian product | |
df = pd.DataFrame([['01-02-2015', 'a', 17], | |
['01-09-2015', 'a', 42], | |
['01-30-2015', 'a', 19], | |
['01-02-2015', 'b', 23], | |
['01-23-2015', 'b', 1], | |
['01-30-2015', 'b', 13]]) | |
df.columns = ['date', 'group', 'response'] | |
df.set_index(['date', 'group'], inplace=True) | |
# Cartesian product of factors to fill missing values | |
date_idx = pd.date_range('01-02-2015', '01-30-2015', freq='7D') | |
group_idx = ['a', 'b'] | |
iterables = [date_idx, group_idx] | |
idx_product = pd.MultiIndex.from_tuple(iterables, names=['date', 'group']) | |
# df.response is all NaN values after this line | |
df = df.reindex(idx_product) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Replacing
date_idx
with strings fixes the issue. Looks like the NaN values are caused bypd.date_range
.