Python pandas Convert a Column to Column Header

时光怂恿深爱的人放手 提交于 2021-02-11 13:30:43

问题


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": 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? Thanks.

#   1 2
# 0 3 6

回答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



回答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")


来源:https://stackoverflow.com/questions/51193459/python-pandas-convert-a-column-to-column-header

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!