Skip to content Skip to sidebar Skip to footer

Python Pandas Convert A Column To Column Header

I've a list of dict contains x and y. I want to make x as the index and y as the column headers. How can I do it? Thanks import pandas pt1 = {'x': 0, 'y': 1, 'val': 3,} pt2 = {'x'

Solution 1:

You can use df.pivot:

pt1 = {"x": 0, "y": 1, "val": 3,}
pt2 = {"x": 0, "y": 2, "val": 6,}
pt3 = {"x": 1, "y": 1, "val": 4,}
pt4 = {"x": 1, "y": 2, "val": 9,}

lst = [pt1, pt2, pt3, pt4]

df = pd.DataFrame(lst)

>>> df
   val  x  y
0    3  0  1
1    6  0  2
2    4  1  1
3    9  1  2


>>> df.pivot('x', 'y', 'val')

y  1  2
x      
0  3  6
1  4  9

Solution 2:

I can only think of using two for loops to do. Any better way? Thanks.

idx = df.x.unique()
cols = df.y.unique()
lst2 = []
for i in idx:
  struc = {"x": i,}
  for c in cols:
    dfval = df.loc[(df.x==i) & (df.y==c)]
    v = dfval.val.values[0]
    struc[c] = v
  lst2.append(struc)
df2 = pandas.DataFrame(lst2).set_index("x")

Post a Comment for "Python Pandas Convert A Column To Column Header"