Pandas知識點(diǎn)-Series數(shù)據(jù)結(jié)構(gòu)介紹

一、Series數(shù)據(jù)結(jié)構(gòu)介紹
# coding=utf-8
import pandas as pd
df = pd.read_csv('600519.csv', encoding='gbk')
data = df['收盤價(jià)']
print(data)
print(type(data))
<class 'pandas.core.series.Series'>
二、創(chuàng)建Series和DataFrame
1. 創(chuàng)建Series
s1 = pd.Series({'a': 10, 'b': 20, 'c': 30, 'd': 40})
print(s1)
print(type(s1))a 10
b 20
c 30
d 40
dtype: int64
<class 'pandas.core.series.Series'>
import numpy as np
s2 = pd.Series(np.random.rand(5), index=[alpha for alpha in 'abcde'])
print(s2)
print(type(s2))a 0.269565
b 0.520705
c 0.419913
d 0.182670
e 0.031500
dtype: float64
<class 'pandas.core.series.Series'>
實(shí)例化一個(gè)Pandas中的Series類對象,即可創(chuàng)建出一個(gè)Series數(shù)據(jù)。傳入Series中的數(shù)據(jù)時(shí),可以傳入一個(gè)字典,每個(gè)鍵值對的key是行索引,value是對應(yīng)的數(shù)據(jù),如上面的s1。也可以傳入一個(gè)一維數(shù)組,然后用index參數(shù)設(shè)置行索引,不設(shè)置行索引時(shí)默認(rèn)為數(shù)值型索引,即從0開始的整數(shù),如上面的s2。
df1 = pd.DataFrame({
'one': s2,
'two': pd.Series(np.random.rand(4), index=[alpha for alpha in 'abcd'])
})
print(df1)
print(type(df1)) one two
a 0.988763 0.592909
b 0.093969 0.674316
c 0.593211 0.253496
d 0.374765 0.565424
e 0.850890 NaN
<class 'pandas.core.frame.DataFrame'>
df2 = pd.DataFrame(np.random.randn(3, 3), index=pd.date_range('1/1/2021', periods=3), columns=['one', 'two', 'three'])
print(df2)
print(type(df2)) one two three
2021-01-01 0.736518 -0.012771 0.459488
2021-01-02 0.665910 0.700380 -1.124228
2021-01-03 -0.418457 -1.907136 -0.207422
<class 'pandas.core.frame.DataFrame'>
三、Series的基本屬性
df = pd.read_csv('600519.csv', encoding='gbk')
s = df['漲跌幅']
print(s.index)RangeIndex(start=0, stop=4726, step=1)
df = pd.read_csv('600519.csv', encoding='gbk')
s = df['漲跌幅']
print(s.values)
print(type(s.values))
print(s.array)['-0.4452' '-4.9981' '5.8854' ... '-1.3022' '3.685' '13.2526']
<class 'numpy.ndarray'>
<PandasArray>
['-0.4452', '-4.9981', '5.8854', '3.6993', '2.4125', '-0.3382', '5.9792',
'2.0937', '1.6915', '-0.3242',
...
'-2.7793', '-1.9765', '-0.0534', '1.2706', '-0.2965', '-0.2426', '1.9791',
'-1.3022', '3.685', '13.2526']
Length: 4726, dtype: object
df = pd.read_csv('600519.csv', encoding='gbk')
s = df['漲跌幅']
print("形狀:", s.shape)
s2 = s.T
print("轉(zhuǎn)置后形狀:", s2.shape)形狀:(4726,)
轉(zhuǎn)置后形狀:(4726,)
四、Series的索引設(shè)置
df = pd.read_csv('600519.csv', encoding='gbk')
s = df['漲跌幅'].head(3)
print(s)
s.index = [alpha for alpha in 'abc']
print(s)0 -0.4452
1 -4.9981
2 5.8854
Name: 漲跌幅, dtype: object
a -0.4452
b -4.9981
c 5.8854
Name: 漲跌幅, dtype: object
s2 = s.reset_index()
print(s2)
print(type(s2))
s3 = s.reset_index(drop=True)
print(s3)
print(type(s3)) index 漲跌幅
0 a -0.4452
1 b -4.9981
2 c 5.8854
<class 'pandas.core.frame.DataFrame'>
0 -0.4452
1 -4.9981
2 5.8854
Name: 漲跌幅, dtype: object
<class 'pandas.core.series.Series'>
評論
圖片
表情
