Python 如何将矩阵转换为熊猫数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26778899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:00:06  来源:igfitidea点击:

How to convert matrix to pandas data frame

pythonpandas

提问by Hangon

I'm trying to convert a matrix into a pandas data frame:

我正在尝试将矩阵转换为熊猫数据框:

matrixA={}
matrixA[0,0]='a'
matrixA[0,1]='b'
matrixA[1,0]='c'
matrixA[1,1]='d'

Like this:

像这样:

import pandas as pd

pd.DataFrame(matrixA)

I get an error.

我收到一个错误。

采纳答案by greole

As already said your are not creating a matrix but a python dictionary. However a dict can serve as parameter to create a dataframe, but you reversed the indexing order.

如前所述,您不是在创建矩阵,而是在创建 python字典。但是,dict 可以作为参数来创建数据帧,但您颠倒了索引顺序。

import pandas as pd

matrixA={}
matrixA['a']=[0,0]
matrixA['b']=[0,1]

pd.DataFrame(matrixA)

   a  b
0  0  0
1  0  1

Additionally you can use numpysmatrix

此外,您可以使用numpys矩阵

import numpy as np

a = np.matrix('1 2; 3 4')
pd.DataFrame(a)

   0  1
0  1  2
1  3  4

回答by mythicalcoder

Well, I was wondering if we could use python's multi-dimensional array. Yes, you can use python matrix (as mentioned in the python official docs) or multi-dimensional arrays and convert into pandas DataFrame.

好吧,我想知道我们是否可以使用python的多维数组。是的,您可以使用python矩阵(如python官方文档中所述)或多维数组并转换为pandas DataFrame。

import pandas as pd
matrix = [
    ["a", 1],
    ["b", 2]
]
pd.DataFrame(matrix)

   0  1
0  a  1
1  b  2