Pandas高級數(shù)據(jù)結構-創(chuàng)建方式

Series的介紹

series的創(chuàng)建

  • 1.通過列表創(chuàng)建
import numpy as numpy
import pandas as pd
s1 = pd.Series([1,2,3,4])
s1

0    1
1    2
2    3
3    4
4    5
dtype: int64
  • 2.通過數(shù)組創(chuàng)建
s2 = pd.Series(np.arange(1,6))
s2


0    1
1    2
2    3
3    4
4    5
dtype: int32

** 注意:上述兩種方式的創(chuàng)建方法列表是int64 數(shù)組是int32

DataFrame

DataFrame創(chuàng)建


  • 1.列表、元組、數(shù)組構成的字典創(chuàng)建dataframe
# 字典的鍵變成列 值變成行填充進去
data = {
    'A':[1,2,3,4],
    'B':(5,6,7,8),
    'C':np.arange(9,13)
}
frame = pd.DataFrame(data)
frame

    A   B   C
0   1   5   9
1   2   6   10
2   3   7   11
3   4   8   12
  • 2.Series構成的字典構造dataframe
pd1 = pd.DataFrame({'a':pd.Series(np.arange(3)),
             'b':pd.Series(np.arange(3,5))})
pd1

    a    b
0   0   3.0
1   1   4.0
2   2   NaN
# 共用一個索引 如果一個列中沒有這行的索引則用nan填充
  • 3.構造二維數(shù)據(jù)對象
arr1 = np.arange(12).reshape(4,3)
arr1

array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])


frame1 = pd.DataFrame(arr1)
frame1

    0   1   2
0   0   1   2
1   3   4   5
2   6   7   8
3   9   10  11
# 通過二維數(shù)組更能清楚的明白numpy和pandas之前的關系
  • 4.字典構成的列表構造dataframe
l1 = [{'apple':3.6,'banana':5.6},{'apple':3,'banana':5},{'apple':3.2}]
pd3 = pd.DataFrame(l1)
pd3


   apple    banana
0   3.6      5.6
1   3.0      5.0
2   3.2      NaN
#把列表中的索引下標當作行索引 字典里的鍵同樣是作業(yè)列索引 然后依次從0開始對于行索引
  • 5.Series構成的列表構造dataframe
l2 = [pd.Series(np.random.rand(3)),pd.Series(np.random.rand(2))]
pd4 = pd.DataFrame(l2)

pd4

       0            1         2
0   0.998996    0.960031    0.988391
1   0.649718    0.316651    NaN

# 列下標作為行索引 series的索引作為列索引 然后依次填入值

原文鏈接:https://blog.csdn.net/weixin_44984627/article/details/104746098

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容