python:pandas之DataFrame创建

1、方案一:

import pandas as pd
import numpy as np
t = pd.DataFrame(np.arange(12).reshape((3,4))) #不指定列索引和行索引
#  t 为一个二维数组:
   0  1   2   3
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
t = pd.DataFrame(np.arange(12).reshape((3,4)),  index=list("abc"),columns=list("WXYZ")  )              # 指定列索引和行索引
#  t 为一个二维数组:
 W  X   Y   Z
a  0  1   2   3
b  4  5   6   7
c  8  9  10  11

2、方案二:字典里套列表

d1 = {"name":["xiaogang","xiaoming"],"age":[20, 22],"tel":[10086,10010]}
t = pd.DataFrame(d1)
# t的输出结果为:
       name  age    tel               #  列索引为字典的key
0  xiaogang   20  10086
1  xiaoming   22  10010

3、方案三:列表里套字典

d2 = [{"name":"xiaogang","age":20,"tel":10086},{"name":"xiaohong","age":20},{"name":"xiaoqiang","tel":10086}]
t = pd.DataFrame(d2)
# t的输出结果为:
    age       name      tel              # 注意,NAN是因为d2列表中的字典中未赋值
0  20.0   xiaogang  10086.0
1  20.0   xiaohong      NaN
2   NaN  xiaoqiang  10086.0

你可能感兴趣的:(python:pandas之DataFrame创建)