美文网首页Python与数据分析
【Python学习笔记】Pandas: DataFrame对象的

【Python学习笔记】Pandas: DataFrame对象的

作者: 清梦载星河 | 来源:发表于2019-08-03 19:03 被阅读0次
镇楼图参上

方法1:由数组或列表组成的字典构建DataFrame(常用)

#字典的键作为列
import pandas as pd

data1 = {'a' : [1,2,3],'b' : [4,5,6], 'c' : [7,8,9]}
df1 = pd.DataFrame(data1)

print(df1)
###########
#   a  b  c
#0  1  4  7
#1  2  5  8
#2  3  6  9

方法2:由Series组成的字典构建DataFrame(常用)

data2 = {'a' : pd.Series(np.random.rand(3)),
         'b' : pd.Series(np.random.rand(3)*10),
         'c' : pd.Series(np.random.rand(3)*100)}
df2 = pd.DataFrame(data2)

print(df2)
#################################
#          a         b          c
#0  0.713086  1.196266  98.645137
#1  0.810221  6.738664  37.399359
#2  0.153884  2.247200  47.458595

方法3:通过二维数组构建DataFrame(常用)

df3 = pd.DataFrame(np.random.randint(10,100,(3,7)))
print(df3)

##############################
#    0   1   2   3   4   5   6
#0  32  89  34  99  96  79  79
#1  35  29  34  21  19  16  30
#2  80  92  65  46  15  60  36

方法4:由字典组成的列表构建DataFrame

data4 = [{'a':1,'b':2},{'a':5,'b':10,'c':15}]
df4 = pd.DataFrame(data4)
print(df4)

###############
#   a   b     c
#0  1   2   NaN
#1  5  10  15.0

方法5:由字典组成的字典构建DataFrame

data5 = {'xiaoming':{'Chinese':np.random.randint(60,100),
                     'Math':np.random.randint(60,100),
                     'Endlish':np.random.randint(60,100)},
         'xiaohong':{'Chinese':np.random.randint(60,100),
                     'Math':np.random.randint(60,100),
                     'Endlish':np.random.randint(60,100)},
         'xiaogang':{'Chinese':np.random.randint(60,100),
                     'Math':np.random.randint(60,100),
                     'Endlish':np.random.randint(60,100)},
        }
df5 = pd.DataFrame(data5)
print(df5)

######################################
#         xiaoming  xiaohong  xiaogang
#Chinese        75        68        86
#Endlish        84        93        87
#Math           61        84        75

相关文章

网友评论

    本文标题:【Python学习笔记】Pandas: DataFrame对象的

    本文链接:https://www.haomeiwen.com/subject/oyhsdctx.html