Python 将行数据转换为表格式
我从按行显示的csv文件中获得信息: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 我通过循环迭代来实现
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