how to create a dataframe using unique columns from other dataframe

Viewed 44

i have 2 columns (A and B) in dataframe (pandas)

column A= AAA CCC AAA FFF RRR CCC
column B= BBB DDD EEE DDD WWW BBB

I want to find unique values in A and B column and need to count the occurrence of each value in column A w.r.t column B

The result should look like this:

     BBB   DDD   EEE  WWW
AAA  1     0     1    0

CCC  1     1     0    0

FFF  0     1     0    0

RRR  0     0     0    1

How to achieve this using pandas in Databricks?

1 Answers

Use Crosstab

df = pd.DataFrame({'column A':['AAA', 'CCC', 'AAA', 'FFF', 'RRR', 'CCC'],
                   'column B':['BBB', 'DDD', 'EEE', 'DDD', 'WWW', 'BBB']})
pd.crosstab(df['column A'], df['column B'])
Related