'Convert a Column to Column Header
I have a list of dict containing x and y. I want to make x the index and y the column headers. How can I do it?
import pandas
pt1 = {"x": 0, "y": 1, "val": 3,}
pt2 = {"x": 0, "y": 2, "val": 6,}
lst = [pt1, pt2]
print(lst)
# [{'x': 0, 'y': 1, 'val': 3}, {'x': 0, 'y': 2, 'val': 6}]
df = pandas.DataFrame(lst)
print(df)
# val x y
# 0 3 0 1
# 1 6 0 2
How can I convert df
to this format?
# 1 2
# 0 3 6
Solution 1:[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:[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")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | K Kontakt |