-1

I have a pandas dataframe that looks like this:

enter image description here

How do I convert it to this:

enter image description here

1 Answers1

1

As you said that the number of x and y are same,

'''
df = pd.DataFrame({
    'category' : ['x'] * 5 + ['y'] * 5,
    'values' : [i for i in range(1, 11)]
})
'''

category_dic = {'x' : [], 'y' : []}

for row in range(len(df)):
    category_dic[df.loc[row, 'category']].append(df.loc[row, 'values'])

df_1 = pd.DataFrame(category_dic)

Output :

>>> df_1
   x   y
0  1   6
1  2   7
2  3   8
3  4   9
4  5  10

※ Edit version(not using globals)

jaemmin
  • 341
  • 1
  • 12
  • x and y are same in number. But I do want to avoid defining globals. Your output is exactly what I want, yet is there no other (pandas) way of solving this? – Zeeshan Asghar Nov 09 '22 at 03:00