I have a pandas.DataFrame with ZIPCODES in two columns. I just want to count the appearence of all ZIPCODES with value_counts(). But it does not matter for me in which column they are. I need a result for all ZIPCODE columns in the DataFrame together.
This is the inital data with ZIPCODES in the columns:
ZIPCODE_A ZIPCODE_B
0 10000 40000
1 20000 30000
2 20000 20000
3 10000 50000
4 30000 10000
The final and expected result would be:
ZIPCODE_N
10000 3
20000 3
30000 2
40000 1
50000 1
Question
My solution works but looks complicated. Is there another more elegant pandas-way to solve this?
MWE
#!/usr/bin/env python3
import pandas as pd
0000
df = pd.DataFrame({'ZIPCODE_A': [10000, 20000, 20000, 10000, 30000],
'ZIPCODE_B': [40000, 30000, 20000, 50000, 10000]})
print(df)
a = df.ZIPCODE_A.value_counts()
b = df.ZIPCODE_B.value_counts()
a = pd.DataFrame(a)
b = pd.DataFrame(b)
r = a.join(b, how='outer')
r.loc[r.ZIPCODE_A.isna(), 'ZIPCODE_A'] = 0
r.loc[r.ZIPCODE_B.isna(), 'ZIPCODE_B'] = 0
r['ZIPCODE_N'] = r.ZIPCODE_A + r.ZIPCODE_B
r.ZIPCODE_N = r.ZIPCODE_N.astype(int)
del r['ZIPCODE_A']
del r['ZIPCODE_B']
print(r)