0 votes
1 view
in Data Science by (17.6k points)

I'm looking for a solution for the case bellow:

How do I pivot df such that the col values become columns when df consist only one dimension?

And how to proceed in order to have in a result in each column made from those rows value 0 or 1 depending on occurrences for each of them in the previous column?

It'll be easier to illustrate it. So from this kind of data frame:

df =

DATA   

cat1

dog1

cat2

dog2

cat3

dog3

...   

to this kind of data frame:

df =

Animal   cat1   dog1   cat2   dog2   cat3   dog3    ...

cat1    1      0      0      0      0      0        ...

dog1    0      1      0      0      0      0        ...

cat2    0      0      1      0      0      0        ...

dog2    0      0      0      1      0      0        ...

cat3    0      0      0      0      1      0        ...

dog3    0      0      0      0      0      1        ...

...   

cat1    1      0      0      0      0      0        ...

dog1    0      1      0      0      0      0        ...

First I've tried to gather all unique values and then I reshaped it to pd.DataFrame because it was a np array. Then I've tried to use pivot. I know that it should have arguments like 'index', 'column' and 'values', but in my case, I have only one dimension (just one column).

to_reschape = df.Animal.unique()

type(to_reschape)

dataset = pd.DataFrame(to_reschape)

dataset.pivot()

KeyError: None

1 Answer

0 votes
by (38.2k points)

You can use the below command:

pd.get_dummies(df.set_index(df.DATA), prefix='', prefix_sep='')

And this will give the output as:

      cat1  cat2  cat3  dog1  dog2  dog3

DATA                                    

cat1     1     0     0     0     0     0

dog1     0     0     0     1     0     0

cat2     0     1     0     0     0     0

dog2     0     0     0     0     1     0

cat3     0     0     1     0     0     0

dog3     0     0     0     0     0     1

dog1     0     0     0     1     0     0

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...