Объект Series обладает своиствами списка, массива и словаря. На первый взгляд это именно то, что надо для работы с CSV файлами. Потому здесь изучаем 20-минутный видеоролик.
Key Learning Objective: Series exhibits both array-like and dict-like properties. Помимо видео внизу мне еще понравился вот этот пост The pandas library is used for all the data analysis excluding a small piece of the data presentation section
Но самый полный список обучающих ресурсов здесь This is a guide to many pandas tutorials, geared mainly for new users
Но самый полный список обучающих ресурсов здесь This is a guide to many pandas tutorials, geared mainly for new users
In [1]:
from IPython.display import YouTubeVideo
YouTubeVideo('eRpFC2CKvao')
Out[1]:
In [50]:
from IPython.display import Image
Image(filename='C:/Users/kiss/Documents/GitHub/pdacookbook/images/series4.jpg',width=200)
Out[50]:
Как я понял идею "скрий"... При создании серии есть данные (список) и есть индекс (список), таким образом, индексом можно назначить, как столбец с цифрами, так и столбец со строками. Попимо индекса, есть еще некий системный аналог - offset. Получается, что любой элемент списка (данных) можно вызвать двумя способами...
Повторяем примеры из видеоролика¶
In []:
# s = Series(data,index=index)
# data may be different lists, including
# a list, an array, a dictionary
In [2]:
import pandas as pd
import numpy as np
In [3]:
s1= pd.Series([33,19,15,89,11,-5,9])
In [4]:
# The default index is not specified in the Series constructor
s1
Out[4]:
In [5]:
type(s1)
Out[5]:
In [6]:
s1.values
Out[6]:
In [7]:
type(s1.values)
Out[7]:
In [8]:
s1.index
Out[8]:
Пример 2. Объект Series with meaningfull labels¶
In [11]:
#define data and index as separate lists
data1=[33,19,15,89,11,-5,9]
index1=['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
In [12]:
s2= pd.Series(data1,index=index1)
In [13]:
# all elements are int64
s2
Out[13]:
In [14]:
s2.index
Out[14]:
In [15]:
s2.name='Dayly Temperatures'
s2.index.name='Weekday'
Третий пример¶
In [16]:
# The second dada element have float '19.3' instead int '19' in data1
data2=[33,19.3,15,89,11,-5,9]
In [17]:
# create new Series with second element
s3= pd.Series(data2,index=index1)
In [19]:
# and we see that all elements are homogeneous (float64)
s3
Out[19]:
Creating a Series from Python Dict¶
In [20]:
dict1={'Mon':33,'Tue':19,'Wed':15,'Thu':89,'Fri':11,'Sat':-5,'Sun':9}
In [21]:
s4= pd.Series(dict1)
In [22]:
s4
Out[22]:
Series in ndArray-like¶
In [23]:
# vectorized operations
s4*2
Out[23]:
In [24]:
np.log(s4)
Out[24]:
Note: NAN (not number) is statdart missing data marking in Pandas
In [26]:
# slice using index labels
s4['Thu':'Wed']
Out[26]:
In [27]:
# slice using position
# there are only two elements s[1] and s[2]
s4[1:3]
Out[27]:
In [29]:
# retreive value using offset
s4[1], s4[2]
Out[29]:
In [30]:
# set value using offset
s4[1]=199
s4
Out[30]:
In [32]:
# as a subclass of ndarray Series is a valid argument for most Numpy functions
s4.median(), s4.max()
Out[32]:
In [33]:
s4.cumsum()
Out[33]:
In [37]:
#looping over a collection and indeces
for i,v in enumerate(s4):
print i,v
In [39]:
#list comprehension can be used to create a new list
new_list=[x**2 for x in s4]
In [40]:
new_list
Out[40]:
Series is dict-like¶
In [42]:
'Sun' in s4
Out[42]:
In [45]:
#retrieve value using key of index
s4['Tue'], s4[5]
Out[45]:
In [46]:
# looping over dictionary keys and values
for k,v in s4.iteritems():
print v,k
In [48]:
from IPython.display import HTML
In [49]:
HTML('<iframe src=http://alfredessa.com/data-analysis-tutorial/2-pandas-library/ width=800 height=350></iframe>')
Out[49]:
Посты чуть ниже также могут вас заинтересовать
Комментариев нет:
Отправить комментарий