Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将行数据转换为表格式_Python_Pandas_Dataframe - Fatal编程技术网

Python 将行数据转换为表格式

Python 将行数据转换为表格式,python,pandas,dataframe,Python,Pandas,Dataframe,我从按行显示的csv文件中获得信息: Color Shape Value red triangle 10 red circle 11 blue triangle 12 blue circle 13 我需要将其转换为矩阵形式的新数据帧,其中列是颜色,索引是形状 red blue triangle 10 12 circle 11 13 我通过循环迭代来实现

我从按行显示的csv文件中获得信息:

Color     Shape    Value
red       triangle    10
red       circle      11
blue      triangle    12
blue      circle      13
我需要将其转换为矩阵形式的新数据帧,其中列是颜色,索引是形状

           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
  ...
  • 我真的不需要对形状进行排序,但我需要保证在每次迭代中检索到的形状列表的顺序相同,否则结果表将是错误的
这行得通,我觉得我做得太过分了。 有没有直接的方法获取行信息并将其转换为表形式


谢谢

您可以使用
pivot\u 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