简体   繁体   English

Python pandas将列转换为列标题

[英]Python pandas Convert a Column to Column Header

I've a list of dict contains x and y. 我有一个字典列表,其中包含x和y。 I want to make x as the index and y as the column headers. 我想将x作为索引,将y作为列标题。 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? 如何将df转换为这种格式? Thanks. 谢谢。

#   1 2
# 0 3 6

You can use df.pivot : 您可以使用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

I can only think of using two for loops to do. 我只能想到使用两个for循环来做。 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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM