0

I have dataframe like

Name   keywords  Count
User1  aws        14
User1  ec2        4
User1  python     1
User2  aws        12
User2  ec2        5
User2  python     6
User3  aws        17
User3  ec2        7
User3  python     8

and so on...

I want to convert values in both Keywords and Count column to rows like except the header 'keywords' and 'Count'

example

Name    aws   ec2  python
User1   14    4     1
User2   12    5     6
User3   17    7     8
Akash
  • 37
  • 1
  • 6
  • You can also try to set a MultiIndex and stack/unstack: https://stackoverflow.com/questions/44365893/stack-unstack-operations-in-pandas – tturbo Oct 17 '22 at 12:10

1 Answers1

1

Reproduced your dataframe with:

df = pd.read_csv(io.StringIO(
"""
Name,keywords,Count
User1,aws,14
User1,ec2,4
User1,python,1
User2,aws,12
User2,ec2,5
User2,python,6
User3,aws,17
User3,ec2,7
User3,python,8
"""
), sep=",")

Then using pivot to produce your desired dataframe:

>>> df.pivot(index="Name", columns="keywords", values="Count")
... keywords  aws  ec2  python
... Name                      
... User1      14    4       1
... User2      12    5       6
... User3      17    7       8

Note that this creates the name as an index. If you would like to have name as as column instead you can reset the index as such:

>>> df.reset_index()
... keywords   Name  aws  ec2  python
... 0         User1   14    4       1
... 1         User2   12    5       6
... 2         User3   17    7       8
Oddaspa
  • 731
  • 5
  • 21