熊猫行数据到表格形式

时间:2018-07-06 10:07:13

标签: python pandas dataframe

我有一个按行显示的csv文件信息:

Color     Shape    Value
red       triangle    10
red       circle      11
blue      triangle    12
blue      circle      13

我需要将其转换为矩阵形式的新dataFrame,其中列为颜色,索引为形状

           red  blue
triangle    10    12
circle      11    13

我设法通过循环遍历

new_df = pd.DataFrame(columns=list_of_colors, index=list_of_shapes)

for color_i in list_of_colors:
  # this gives me the values of each color sorted* by Shape
  df[df['Color'] == color_i].sort_values('Shape')['Value']

  # so I can append this to the new dataframe
  ...
  • 我真的不需要对形状进行排序,但我需要保证在每次迭代中,检索到的形状列表的顺序都相同,否则结果表将是错误的

这行得通,我认为我做得太过分了。 是否有直接的方法来获取行信息并将其转换为表格形式?

谢谢

1 个答案:

答案 0 :(得分:3)

您可以使用pivot_table()

对于数据: 将熊猫作为pd导入

df = pd.DataFrame({'Color': ['red', 'red', 'blue', 'blue'],
                   'Shape': ['triangle', 'circle', 'triangle', 'circle'],
                   'Value': [10, 11, 12, 13]})


df.pivot_table(index = 'Color', columns = 'Shape', values = 'Value')

结果是:

Shape   circle  triangle
Color       
blue     13       12
red      11       10