1. 程式人生 > >第十五章 pandas官方文件0.22中文教程---Tutorials(lessons 4 lessons 5),個人渣翻譯

第十五章 pandas官方文件0.22中文教程---Tutorials(lessons 4 lessons 5),個人渣翻譯

這裡寫圖片描述

Lesson 4 –新增/刪除列-索引操作

在這節課中我們將回到基礎。我們將使用一個小的資料集,這樣您就可以很容易地理解我要解釋的內容。我們將新增列、刪除列,並以許多不同的方式分割資料。享受吧!

import pandas as pd
# Our small data set
d = [0,1,2,3,4,5,6,7,8,9]

# Create dataframe
df = pd.DataFrame(d)
df

這裡寫圖片描述

# Lets change the name of the column
df.columns = ['Rev']
df
# Lets add a column
df['NewCol'] = 5 df

這裡寫圖片描述

# Lets modify our new column
df['NewCol'] = df['NewCol'] + 1
df

這裡寫圖片描述

# We can delete columns
del df['NewCol']
df

這裡寫圖片描述

# Lets add a couple of columns
df['test'] = 3
df['col'] = df['Rev']
df

這裡寫圖片描述

# If we wanted, we could change the name of the index
i = ['a','b','c','d','e','f'
,'g','h','i','j'] df.index = i df

這裡寫圖片描述
現在我們可以開始使用loc選擇dataframe的片段。

df.loc['a']

這裡寫圖片描述

# df.loc[inclusive:inclusive]
df.loc['a':'d']

這裡寫圖片描述
我們還可以選擇使用列名

df['Rev']
df[['Rev', 'test']]

這裡寫圖片描述

df.loc[df.index[0:3],'Rev']

這裡寫圖片描述

Lessons 5 Stack/Unstack/轉置函式
# Our small data set
d = {'one':[1,1],'two':[2,2]}
i = ['a'
,'b'] # Create dataframe df = pd.DataFrame(data = d, index = i) df

這裡寫圖片描述

df.index

這裡寫圖片描述

stack = df.stack()
stack

這裡寫圖片描述

# The index now includes the column names
stack.index

這裡寫圖片描述

unstack = df.unstack()
unstack

這裡寫圖片描述
(列索引變成行索引,層次不一樣。)
這裡寫圖片描述
我們還可以使用T(轉置)函式來使用索引來翻轉列名

transpose = df.T
transpose

這裡寫圖片描述

transpose.index

這裡寫圖片描述