How do I include terms with zero crossings in a pandas group?

How to output the result of pandas

groupby - including zero cross-terms to a csv file.

A toy example of exactly what I'm looking for:

I have a pandas

dataframe that can be approximated like this:

df = pd.DataFrame(np.random.choice(['A', 'B', 'C'], (10, 2)), 
                  columns=['one', 'two'])

      

Which gave me the following:

   one  two
0   C   C
1   C   A
2   A   B
3   B   A
4   B   C
5   B   B
6   C   C
7   A   C
8   C   B
9   C   C

      

When I start the group, it works as expected:

grouped = df.groupby(['one', 'two']).size()
grouped

one  two
A    B      1
     C      1
B    A      1
     B      1
     C      1
C    A      1
     B      1
     C      3
dtype: int64

      

However, I would like to include the term "AA 0" because I am writing this to a csv file:

grouped.to_csv("test1.csv", header=True)

!cat test1.csv

one,two,0
A,B,1
A,C,1
B,A,1
B,B,1
B,C,1
C,A,1
C,B,1
C,C,3

      

And I want the file to include the line: A,A,0

.

+3


source to share


1 answer


You can do it with unstack:

grouped.unstack('two').fillna(0).stack()



which gives for example the following output:

one  two
A    A      2
     B      1
     C      1
B    A      0
     B      1
     C      3
C    A      2
     B      0
     C      0

      

+4


source







All Articles