Created
May 5, 2022 22:32
-
-
Save sss-ng/ced3a287e8843cdfc232617f69507456 to your computer and use it in GitHub Desktop.
pandas groupby reindex not working as expected
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 | |
dates = pd.date_range("2020-01-01", "2020-01-10", freq="1D", tz="UTC") | |
df = pd.DataFrame( | |
[ | |
{"state": "virginia", "count": 4}, | |
{"state": "virginia", "count": 5}, | |
{"state": "virginia", "count": 2}, | |
{"state": "virginia", "count": 8}, | |
{"state": "virginia", "count": 0}, | |
{"state": "virginia", "count": 3}, | |
{"state": "virginia", "count": 7}, | |
{"state": "virginia", "count": 0}, | |
{"state": "virginia", "count": 4}, | |
{"state": "virginia", "count": 2}, | |
] | |
) | |
df["date"] = dates | |
df = df.set_index("date") | |
new_dates = pd.date_range("2020-01-01", "2020-01-10", freq="1D", tz="UTC") | |
df = df.groupby(["state"]).apply(lambda x: x.reindex(new_dates, fill_value=0)) | |
print(df) |
Author
sss-ng
commented
May 6, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment