将pandas索引转换为numpy数组。蟒蛇

时间:2017-09-19 01:30:42

标签: python pandas numpy

我想将数据框的索引列转换为数组,但我不知道如何去做。我已经将第二列转换为数组,但由于某种原因它也不能在第一列上运行。以下是我尝试转换索引列的方法:

time = df1.as_matrix(columns = df1.columns[:,0])

但是我得到了

too many indices for array

这是我的数据框

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

3 个答案:

答案 0 :(得分:6)

您可以df.index.values

df = pd.DataFrame(index=['a', 'b', 'c'])

df.index.values
# array(['a', 'b', 'c'], dtype=object)

答案 1 :(得分:0)

试试time = df1.as_matrix(columns=df1.columns[0:1])。看起来列应该是一维数组(实际上,Index),并且给一维数组提供两个索引会产生错误。

答案 2 :(得分:0)

根据pandas 0.24.x release notes:“添加了Series.array和 Index.array来提取支持Series或Index的数组 ...我们尚未删除或弃用Series。值或DataFrame.values,但我们强烈建议并使用constexpr operator int&() { return value; } constexpr operator const int&() const { return value; } .array

看起来这个主要版本更新确实满足您的需求:)