【3】数据分析--10--科学计算--Pandas--8--numpy的ndarray与pandas的series和dataframe之间互转

data可以为list、series、hash

代码示例

import numpy as np
import pandas as pd
from pandas import Series,DataFrame
data = [[2000,'Ohino',1.5],
        [2001,'Ohino',1.7],
        [2002,'Nevada',2.4]]
ser = Series(data,index=['one','two','three'])

print 'Ser的结果:\n'
print ser

df = DataFrame(data,index=['one','two','three'],columns=['year','state','pop'])

print '\ndataframe的结果:\n'
print df

foo = ser.as_matrix()

print '\n ser to matrix的结果:\n'
print foo

foo = df.as_matrix()

print '\n dataframe to matrix的结果:\n'
print foo

foo_2 = np.array(df)

print '\n dataframe to array的结果:\n'
print foo_2


foo_3 = df.as_matrix(['pop'])
print '\n dataframe to array的结果:\n'
print foo_3

输出结果

Ser的结果:

one       [2000, Ohino, 1.5]
two       [2001, Ohino, 1.7]
three    [2002, Nevada, 2.4]
dtype: object

dataframe的结果:

       year   state  pop
one    2000   Ohino  1.5
two    2001   Ohino  1.7
three  2002  Nevada  2.4

 ser to matrix的结果:

[list([2000, 'Ohino', 1.5]) list([2001, 'Ohino', 1.7])
 list([2002, 'Nevada', 2.4])]

 dataframe to matrix的结果:

[[2000 'Ohino' 1.5]
 [2001 'Ohino' 1.7]
 [2002 'Nevada' 2.4]]

 dataframe to array的结果:

[[2000 'Ohino' 1.5]
 [2001 'Ohino' 1.7]
 [2002 'Nevada' 2.4]]
[[1.5]
 [1.7]
 [2.4]]

参考资料

个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn

Sam avatar
About Sam
专注生物信息 专注转化医学