####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