Note: I had difficulty wording the title of my question, so if you can think of something better to help other people with a similar question, please let me know and I will change it.
Stored as a Pandas DataFrame
print(df)
week | site | vol
1 | a | 10
2 | a | 11
3 | a | 2
1 | b | 55
2 | b | 1
1 | c | 69
2 | c | 66
3 | c | 23
Notice that site b has no data for week 3
week | site | vol
1 | a | 10
2 | a | 11
3 | a | 2
1 | b | 55
2 | b | 1
3 | b | 0
1 | c | 69
2 | c | 66
3 | c | 23
Essentially, I want to create rows for all of the unique combinations of week
and site
. If the original data doesn't have a vol
for a week-site
combo, then it gets a 0
.
Using stack
with unstack
df.set_index(['week','site']).unstack('week',fill_value=0).stack().reset_index()
Out[424]:
site week vol
0 a 1 10
1 a 2 11
2 a 3 2
3 b 1 55
4 b 2 1
5 b 3 0
6 c 1 69
7 c 2 66
8 c 3 23
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments