2018年5月17日 星期四

Coursera - Applied Data Science with Python 學習筆記 01 - Introduction

5月初的放假期間開始了一個Coursera 的 Python Specialization 課程-<Applied Data Science with Python>, 暫時完成了3/5的課,在5月尾開始下一課前,先重溫一下第一課:<Introduction to Data Science in Python> 一些值得記著的codings.

1. 例子

# 關於資料結構
x = (1, 'a', 2, 'b')  # Tuple
x = [1, 'a', 2, 'b']  # List
      # set(x['name'] for x in df).   elist = [n for n in range(0,100) if n%2==0]
x = {1: 'a', 2: 'b'} # Dict
      # x[name], x.values(), x.items()
x = np.array([[7, 8, 9], [10, 11, 12]])     # Array:   import numpy as np.
x = Series(['item1', 'item2', 'item3'], [0, 1, 2])   # Series:  import pandas as pd
x = Dataframe(array, index, columns)   # Dataframe:  import pandas as pd
type()

# 字串 及 正則表示式
x = 'This is a string'
x[0:2]   # 從第 0th 元素開始,停止在第 2nd 元素之前
'This is a string'.split(' ')[0]  # 以空格 '  ' 分拆字串,提取第 0th 元素
re.findall(r'\w+', 'This is a string')  # 以正則表示式尋找特定字符。需要先 import re

# Numpy 中的 Array,用於使用 Vector、Matrix 的時候
a = np.arrange(start, end, step)  # 從 start 至 end,數值間隔為 step 的 Array
a = np.linspace(start, end, count)  # 從 start 至 end,count 個數值的 Array
amax = a.argmax()  # Array 中的最大值
a = np.vstack([array1, array2])  # 垂直合併兩個 Array
arrar2 = array1.copy   # 複製出獨立的 Array


# Pandas 中的 Series/Dataframe, 從 Numpy 的 Array衍生出來,處理數據的資料表時可以用到
a.argmax()
s.loc['name']   # index 為'name'的資料
df.reset_index()  # 重設 index 為 0:len(df)
df.set_index('time').sort_index()  # 以Column 'time' 為 index,並排序
df.dropna()  # 除去包含 NA 的行-Row
df.apply(min_max, axis=1)  # 進行 Row 運算
df.pivot_table(values, index, columns, aggfunc=[np.mean,np.min], margins=True)  # 製作Pivot Table綜合資料表
df= df.set_index('Col1') .groupby(level=0)['Col2'].agg({'avg': np.average}) 
pd.cut(df['avg'],10)



# 有關 Function:
def add_numbers(x,y):
  return x+y
my_function = lambda a, b, c : a + b
map(function, list1, list2)

# 日期時間:
dtnow = dt.datetime.fromtimestamp(tm.time())
tomorrow = dt.date.today() + dt.timedelta(days = 1)
t1 = pd.date_range('2018-01-01', periods=9, freq='2W-SUN')
t2 = pd.Series([1,2,3], [pd.Period('2018-03'), pd.Period('2018-05'), pd.Period('2018-06')])
t2.resample('Q').mean()

# 分佈/統計:
distribution = np.random.binomial(n, p, size)
distribution = np.random.uniform(a, b, size)
distribution = np.random.normal(mean, std, size)
distribution = np.random.chisquare(k, size)
distribution = np.random.poisson(lambda, size)

stats.kurtosis(distribution)   # import scipy.stats as stats
stats.skew(distribution)
stats.ttest_ind(array1, array2)   # 兩樣本平均值的 t-test 

2. 功課

要拎證書,更重要是功課上需要到的 skills:

# 讀取 CSV 資料
df = pd.read_csv('filepath', index_col, skiprows)
# 讀取 Excel 資料 1
df = pd.read_excel('filepath', sheet_name, skiprows, skip_footer, header, usecols, names, na_values)
# 讀取 Excel 資料 2
xl = pd.ExcelFile('filepath')
df = xl.parse("Sheet1") 
# 文字檔
with open('filepath') as f:
for line in f:
    thisLine = line[:-1]

    #lines for categories
    if thisLine[-6:] == '[]':
        category = thisLine[:-6]
        continue
    #lines for sub-categories
    if '(' in line:
        subCategory = thisLine[:thisLine.index('(')-1]
    else:
        subCategory = thisLine
    #combine as data pairs
    cat_subs.append([category, subCategory])
    #clear version of file's lines
    data.append(thisLine)
df = pd.DataFrame(cat_subs, columns = ['Category', 'SubCategory'])

# Column 和 Column Name 的處理
columns_to_keep = ['...', '...', '...']
df = df[columns_to_keep]
df = df.rename(index=str, columns={'OldName':'NewName'})

# 對文字內容的處理(Regular Expression)
df['Col'] = df['Col'].str.replace('\d+', '') \
    .str.replace('\(.*\)','')
df['Col'] = df['Col'].replace('Republic of Korea', 'South Korea')

df = df[df['Col'] == target]   # 對row作條件式的選取
Series = df['Col_1'] + df['Col_2']   # 對column作運算,製造新的 Series
df['NewCol'] = df['Col_1'] + df['Col_2']   # 對column作運算,製造新的列

df['ColName'].argmax()   # 找出某列的最大值
df.set_index('Col_1')['Col_2'].idxmax()   # 找出某列'Col_2'最大值對應的'Col_1' (要先將Col_1設定為index)
df['maxInRow'] = df.max(axis=1)   # 找出每行row的最大值

# 兩層的 index
df.set_index('Col_Item').groupby("Col_Group")['Col'].nlargest(3)

# 以 Left-Join 合併 Dataframe
df = pd.merge(df1.where(df1['criteriaCol']<=target).dropna(), df2, how='left', left_on='Col', right_on='Col')




沒有留言:

張貼留言