我如何将 numpy 数组转换为 Pandas 数据帧

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29978241/
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-09-13 23:17:41  来源:igfitidea点击:

how do i convert a numpy array to pandas dataframe

pythonnumpypandas

提问by I am not George

How do i convert a numpy array to a pandas dataframe?

如何将 numpy 数组转换为 Pandas 数据框?

for example:

例如:

test = np.array([[1,2],[2,3]])
test2 = np.array([[2,4],[2,5]])

to this:

对此:

pd.DataFrame({'test':[[1,2],[2,3]],
              'test2':[[2,4],[2,5]]})

     test   test2
0  [1, 2]  [2, 4]
1  [2, 3]  [2, 5]

采纳答案by unutbu

Although you could use

虽然你可以使用

In [85]: pd.DataFrame({'test':test.tolist(), 'test2':test2.tolist()})
Out[85]: 
     test   test2
0  [1, 2]  [2, 4]
1  [2, 3]  [2, 5]

computation on the NumPy arrays would probably be much faster than an equivalent computation done on a Pandas DataFrame whose columns contain Python lists.

在 NumPy 数组上的计算可能比在 Pandas DataFrame 上执行的等效计算快得多,该 Pandas DataFrame 的列包含 Python 列表。

回答by Andy Hayden

If these numpy arrays have the same length, then Panelmay be a preferable:

如果这些 numpy 数组具有相同的长度,那么Panel可能更可取:

In [11]: p = pd.Panel({"test": test, "test2": test2})

In [12]: p
Out[12]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 2 (minor_axis)
Items axis: test to test2
Major_axis axis: 0 to 1
Minor_axis axis: 0 to 1

In [13]: p["test"]  # a DataFrame
Out[13]:
   0  1
0  1  2
1  2  3