如何使用PANDAS / Python将矩阵转换为列数组

编程入门 行业动态 更新时间:2024-10-27 02:20:07
本文介绍了如何使用PANDAS / Python将矩阵转换为列数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要将Matriz(如下)转换为3列列表。

I need to convert a matriz (below) into a 3 column list.

我目前有一个这样的DataFrame:

I currently have a DataFrame as this:

A B C ... a 1 3 4 ... b 4 0 6 ... c 9 8 0 ...

,我需要得到这样的结果:

and I need to get a results as this:

Source Target Weight a A 1 a B 3 a C 4 b A 4 b C 6 c A 9 c B 8

我一直在尝试使用pandas.pivot_table函数,但无法获得所需的结果。

I've been trying to use pandas.pivot_table function, but I can't get the result needed.

推荐答案

您可以使用 DataFrame.stack()方法:

In [335]: df.stack().reset_index().rename(columns={'level_0':'Source','level_1':'Target', 0:'Weight'}) Out[335]: Source Target Weight 0 a A 1 1 a B 3 2 a C 4 3 b A 4 4 b B 0 5 b C 6 6 c A 9 7 c B 8 8 c C 0

更多推荐

如何使用PANDAS / Python将矩阵转换为列数组

本文发布于:2023-10-27 03:47:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532216.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   矩阵   转换为   如何使用   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!