简体   繁体   English

将 Pandas Dataframe 日期索引和列转换为 Numpy 数组

[英]Convert Pandas Dataframe Date Index and Column to Numpy Array

How can I convert 1 column and the index of a Pandas dataframe with several columns to a Numpy array with the dates lining up with the correct column value from the dataframe?如何将具有多列的 Pandas 数据框的 1 列和索引转换为日期与数据框中正确列值对齐的 Numpy 数组?

There are a few issues here with data type and its driving my nuts trying to get both the index and the column out and into the one array!!这里有一些数据类型问题,它让我发疯,试图将索引和列都取出并放入一个数组中!!

Help would be much appreciated!帮助将不胜感激!

如果A是数据框和col列:

import pandas as pd output = pd.np.column_stack((A.index.values, A.col.values))

IIUC you need values : IIUC 你需要的values

start = pd.to_datetime('2015-02-24')
rng = pd.date_range(start, periods=5)

df = pd.DataFrame({'a': range(5), 'b':list('ABCDE')}, index=rng)  
print (df)
            a  b
2015-02-24  0  A
2015-02-25  1  B
2015-02-26  2  C
2015-02-27  3  D
2015-02-28  4  E

print (df.values)
[[0 'A']
 [1 'B']
 [2 'C']
 [3 'D']
 [4 'E']]

if need index values also first convert datetime to string values in index and then use reset_index for converting index to column:如果需要索引值,也首先将datetime时间转换为index string值,然后使用reset_indexindex转换为列:

df.index = df.index.astype(str)
print (df.reset_index().values)
[['2015-02-24' 0 'A']
 ['2015-02-25' 1 'B']
 ['2015-02-26' 2 'C']
 ['2015-02-27' 3 'D']
 ['2015-02-28' 4 'E']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM