gpt4 book ai didi

python - Pandas 将行数据转换为表格形式

转载 作者:行者123 更新时间:2023-11-30 22:12:08 24 4
gpt4 key购买 nike

我有来自按行显示的 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_table():

对于数据:将 pandas 导入为 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

关于python - Pandas 将行数据转换为表格形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51207964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com