如何在 Pandas 数据帧的列中存储 numpy 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19574258/
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
How to store a numpy arrays in a column of a Pandas dataframe?
提问by MLister
Is it possible to store arbitrary numpyarrays as the values of a singlecolumn in a dataframe of Pandas?
是否可以将任意numpy数组存储为数据框中的单个列的值Pandas?
The arrays are all 2-dimensional, and I intend to use them to calculate values for other columns in the same dataframe.
数组都是二维的,我打算用它们来计算同一数据帧中其他列的值。
To provide some context of what I'm trying to do here:
提供一些我在这里尝试做的事情的背景:
Each array is an adjacency matrix of some network, and for each network I want to calculate its various characteristics (e.g. density, centralities, clustering coefficient, etc) which are in fact other columns in the same dataframe.
每个数组都是某个网络的邻接矩阵,对于每个网络,我想计算它的各种特征(例如密度、中心性、聚类系数等),这些特征实际上是同一数据帧中的其他列。
采纳答案by Boud
Store them as elements as you would do for any other data:
将它们存储为元素,就像您对任何其他数据所做的一样:
import numpy as np
import pandas as pd
a = np.arange(10).reshape(2,5)
b = np.arange(10, 20).reshape(2,5)
pd.DataFrame({'foo':[42,51], 'arr':[a,b]})
Out[10]:
arr foo
0 [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] 42
1 [[10, 11, 12, 13, 14], [15, 16, 17, 18, 19]] 51
Note that what you try to do sounds more to use a Panel.
请注意,您尝试做的事情听起来更像是使用Panel.
回答by cc7768
What do you mean store arbitrary numpy arrays as the values of a column in a dataframe of Pandas?
您是什么意思将任意 numpy 数组存储为 Pandas 数据框中的列值?
Something like this?
像这样的东西?
import numpy as np
import pandas as pd
x = np.random.randn(50, 25)
random_frame = pd.DataFrame(x)
This will store the array x in a DataFrame where the column names are 0, 1, 2, 3... Could you clarify? I think this is more a comment, but I don't know if I can comment yet.
这会将数组 x 存储在列名称为 0、1、2、3 的 DataFrame 中......你能澄清一下吗?我认为这更像是评论,但我不知道我是否可以评论。

