pandas 将熊猫索引转换为 numpy 数组。Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46290436/
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
Converting pandas index to numpy array. Python
提问by alex anderson
I want to convert the index column of a dataframe into an array, but I'm not sure how to go about it. I have already converted the second column to array, but for some reason it doesn't work on the first column as well. Here is how I'm trying to convert the index column:
我想将数据帧的索引列转换为数组,但我不确定如何去做。我已经将第二列转换为数组,但由于某种原因它也不适用于第一列。这是我尝试转换索引列的方式:
time = df1.as_matrix(columns = df1.columns[:,0])
But I get
但我得到
too many indices for array
Here is my dataframe
这是我的数据框
df1
Out[13]:
0
2015-11-19 23:59:54.500 -20.186533
2015-11-19 23:59:54.625 -20.272575
2015-11-19 23:59:54.750 -20.185249
2015-11-19 23:59:54.875 -20.247126
2015-11-19 23:59:55.000 -20.205975
2015-11-19 23:59:55.125 -20.281376
2015-11-19 23:59:55.250 -20.238962
2015-11-19 23:59:55.375 -20.300100
2015-11-19 23:59:55.500 -20.311625
2015-11-19 23:59:55.625 -20.264126
2015-11-19 23:59:55.750 -20.266762
2015-11-19 23:59:55.875 -20.224825
2015-11-19 23:59:56.000 -20.211288
2015-11-19 23:59:56.125 -20.163288
2015-11-19 23:59:56.250 -20.254587
2015-11-19 23:59:56.375 -20.125738
2015-11-19 23:59:56.500 -20.146749
2015-11-19 23:59:56.625 -20.161976
2015-11-19 23:59:56.750 -20.126276
2015-11-19 23:59:56.875 -20.082863
2015-11-19 23:59:57.000 -20.030237
2015-11-19 23:59:57.125 -20.098312
2015-11-19 23:59:57.250 -20.146214
2015-11-19 23:59:57.375 -20.030476
2015-11-19 23:59:57.500 -20.018661
2015-11-19 23:59:57.625 -20.029900
2015-11-19 23:59:57.750 -19.970963
2015-11-19 23:59:57.875 -19.994637
2015-11-19 23:59:58.000 -20.097612
2015-11-19 23:59:58.125 -19.952700
回答by Psidom
You can just do df.index.values
:
你可以这样做df.index.values
:
df = pd.DataFrame(index=['a', 'b', 'c'])
df.index.values
# array(['a', 'b', 'c'], dtype=object)
回答by Jeremy McGibbon
Try time = df1.as_matrix(columns=df1.columns[0:1])
. It looks like columns should be a 1-dimensional array (well, actually, an Index
), and giving two indices to a 1-dimensional array would give that error.
试试time = df1.as_matrix(columns=df1.columns[0:1])
。看起来列应该是一个一维数组(好吧,实际上是一个Index
),并且为一维数组提供两个索引会产生该错误。
回答by mork
according to pandas 0.24.x release notes: "Series.array and Index.array have been added for extracting the array backing a Series or Index... We haven't removed or deprecated Series.values or DataFrame.values, but we highly recommend and using .array
or .to_numpy()
"
根据pandas 0.24.x 发行说明:“添加了Series.array 和Index.array 以提取支持系列或索引的数组......我们没有删除或弃用Series.values 或DataFrame.values,但我们高度评价推荐和使用.array
或.to_numpy()
“
Looks like this major version update does exactly what you need :)
看起来这个主要版本更新完全符合您的需要:)