三、Pandas小結(1)—Series & DataFrame & 索引

# 一. Series

import pandas as pd

#1、創建Series
countries = ['中國','美國','澳大利亞']
countries_s = pd.Series(countries)
print(type(countries_s))
print(countries_s)

numbers = [4,5,6]
print(pd.Series(numbers))

country_dicts = {'CH': '中國',
                'US': '美國',
                'AU': '澳大利亞'}

country_dict_s = pd.Series(country_dicts)
# 給索引命名
country_dict_s.index.name = 'Code'
# 給數據命名
country_dict_s.name = 'Country'

print(country_dict_s)
print(country_dict_s.values)
print(country_dict_s.index)

#2、處理缺失數據
countries = ['中國', '美國', '澳大利亞', None]
print(pd.Series(countries))

numbers = [4, 5, 6, None]
print(pd.Series(numbers))

#3、Series 索引
country_dicts = {'CH': '中國',
                'US': '美國',
                'AU': '澳大利亞'}

country_dict_s = pd.Series(country_dicts)
print(country_dict_s)

# 通過索引判斷數據是存在
# Series也可看作定長、有序的字典
print('CH' in country_dict_s)
print('NZ' in country_dict_s)

print('iloc: ', country_dict_s.iloc[2]) #位置索引
print('loc: ', country_dict_s.loc['CH']) #標籤索引
print('[]:', country_dict_s['US'])

print('iloc:\n', country_dict_s.iloc[[0, 2]])
print()
print('loc:\n', country_dict_s.loc[['US', 'AU']])

# 4、向量化操作
import numpy as np

s = pd.Series(np.random.randint(0, 1000, 10000))
print(s.head()) #c參數爲空,默認爲5
print(s.head(10)) 
print(len(s))

%%timeit -n 100
total = 0
for item in s:
    total += item

%%timeit -n 100
total = np.sum(s)

%%timeit -n 10
s = pd.Series(np.random.randint(0, 1000, 10000))
for label, value in s.iteritems():
    s.loc[label] = value + 2

%%timeit -n 10
s = pd.Series(np.random.randint(0, 1000, 10000))
s += 2

# 二、DataFrame

# 1、創建Dataframe
import pandas as pd

country1 = pd.Series({'Name': '中國',
                    'Language': 'Chinese',
                    'Area': '9.597M km2',
                     'Happiness Rank': 79})

country2 = pd.Series({'Name': '美國',
                    'Language': 'English (US)',
                    'Area': '9.834M km2',
                     'Happiness Rank': 14})

country3 = pd.Series({'Name': '澳大利亞',
                    'Language': 'English (AU)',
                    'Area': '7.692M km2',
                     'Happiness Rank': 9})

df = pd.DataFrame([country1, country2, country3], index = ['CH', 'US', 'AU'])
# 注意在jupyter中使用print和不使用print的區別
print(df)
df

# 添加數據
# 如果個數小於要求的個數,會自動進行“廣播”操作
# 如果大於要求的個數,會報錯
df['Location'] = '地球'
print(df)

df['Region'] = ['亞洲', '北美洲', '大洋洲']
# print(df)
df

# 2、Dataframe索引
#標籤索引
print('loc:')
print(df.loc['CH'])
print(type(df.loc['CH']))
# 位置索引
print('iloc:')
print(df.iloc[1])
# 列索引
print(df['Area'])
print(type(df['Area']))

# 獲取不連續的列數據
print(df[['Language', 'Location']])

# 混合索引
# 注意寫法上的區別
print('**************************')
print('先取出列,再取行:')
print(df['Area']['CH'])
print(df['Area'].loc['CH'])
print(df['Area'].iloc[0])

print('先取出行,再取列:')
print(df.loc['CH']['Area'])
print(df.iloc[0]['Area'])

# 轉換行和列
print(df.T)

# 3、刪除數據
print(df.drop(['CH']))
# 注意drop操作只是將修改後的數據copy一份,而不會對原始數據進行修改
print(df)

print(df.drop(['CH'], inplace=True))
# 如果使用了inplace=True,會在原始數據上進行修改,同時不會返回一個copy
print(df)

#  如果需要刪除列,需要指定axis=1
print(df.drop(['Area'], axis=1))
print(df)

# 也可直接使用del關鍵字
del df['Name']
print(df)

# 4、DataFrame的操作與加載
df['Happiness Rank']

# 注意從DataFrame中取出的數據進行操作後,會對原始數據產生影響
ranks = df['Happiness Rank']
ranks += 2
print(ranks)
print(df)

# 注意從DataFrame中取出的數據進行操作後,會對原始數據產生影響
# !!!安全的操作是使用copy()!!!
ranks = df['Happiness Rank'].copy()
ranks += 2
print(ranks)
print(df)

# 加載csv文件數據
reprot_2015_df = pd.read_csv('./2015.csv')
print('2015年數據預覽:')
#print(reprot_2015_df.head())
reprot_2015_df.head()

print(reprot_2015_df.info())

# 三、索引

# 使用index_col指定索引列
# 使用usecols指定需要讀取的列
reprot_2016_df = pd.read_csv('./2016.csv', 
                             index_col='Country',
                             usecols=['Country', 'Happiness Rank', 'Happiness Score', 'Region'])
# 數據預覽
reprot_2016_df.head()

print('列名(column):', reprot_2016_df.columns)
print('行名(index):', reprot_2016_df.index)

# 注意index是不可變的
reprot_2016_df.index[0] = '丹麥'

# 重置index
# 注意inplace加與不加的區別
reprot_2016_df.reset_index(inplace=True)

reprot_2016_df.head()

# 重命名列名,注意inplace的使用
reprot_2016_df.rename(columns={'Region': '地區', 'Happiness Rank': '排名', 'Happiness Score': '幸福指數'},
                     inplace=True)

reprot_2016_df.head()

# 四、Boolean Mask

reprot_2016_df.head()

only_western_europe_10 = (reprot_2016_df['地區'] == 'Western Europe') & (reprot_2016_df['排名'] > 10) 
only_western_europe_10
# 疊加 boolean mask 得到最終結果
reprot_2016_df[only_western_europe_10]
#合併寫法
reprot_2016_df[(reprot_2016_df['地區'] == 'Western Europe') & (reprot_2016_df['排名'] > 10)]


# 五、 層級索引

reprot_2015_df.head()

# 設置層級索引
report_2015_df2 = reprot_2015_df.set_index(['Region', 'Country'])
report_2015_df2.head(20)

# level0 索引
report_2015_df2.loc['Western Europe']

# 兩層索引
report_2015_df2.loc['Western Europe', 'Switzerland']

# 交換分層順序
report_2015_df2.swaplevel()

# 排序分層
report_2015_df2.sort_index(level=0)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章