import pandas as pd
import numpy as np
se = pd.Series([1,2,3],index=['a','b','c'])
print(se)
print("索引:")
print(se["b"])
print(se[1])
print(se[['b','c']])
print(se.index)
print(se.values)
print("创建DataFrame:")
df_1 = pd.DataFrame([[1,2,3],[4,5,6]],index=['NO1','NO2'],columns=["a","b","c"])
print(df_1)
data = {'id':[0,1,2],'name':['Bob','Jerry','Tom']}
df_2 = pd.DataFrame(data)
print(df_2)
print("打印DataFrame信息:")
print(df_2.info())
print(type(df_2.values))
print(df_2.index)
print(df_2.columns)
print(df_2.ndim)
print("DataFrame筛选:")
print("列筛选:")
print(df_2['id'])
print("行筛选:")
print(df_2.loc[1])
print("下标筛选:")
print(df_2.iloc[1,1])
print("花式索引:")
print(df_2.iloc[[0,2],1])
print("添加一列:")
print(df_2)
df_2['scores'] = [99,99,99]
print(df_2)
print("添加一行:")
print(df_2)
df_2.loc[3] = [1,"Mary",99]
print(df_2)
# print("删除:")
# print("删除一行:")
# #inplace参数:控制删除后的DataFrame是否代替原DataFrame对象,默认为False为不替代
# #axis控制对行还是列进行操作,0为对行,1为对列
# df_2.drop(3,axis=0,inplace=True)
# #也可以 df_2 = df_2.drop(3,axis=0)
# print(df_2)
# print("同时删除两列:")
# df_2.drop(['id','scores'],axis=1,inplace=True)
# print(df_2)
# print("同时删除某行某列:")
# df_2 = df_2.drop(index=[0,3],columns='id')
# print(df_2)
print("多个DataFrame进行运算:")
#+ - * / % 都可以使用
se_1 = pd.Series(np.arange(4),index=list('abcd'))
se_2 = pd.Series(np.arange(4,8),index=list("acer"))
print(se_1)
print(se_2)
print(se_1+se_2)
#add() sub() mul() div() mod()
add_value = se_1.add(se_2)
print(add_value)
add_value = se_1.add(se_2,fill_value=0) #fill_value:在没有值的位置填充相应数值
print(add_value)
df_1 = pd.DataFrame([[1,1,1],[2,2,2]],index=list('ab'),columns=list("qwe"))
df_2 = pd.DataFrame([[2,2,2],[2,2,2]],index=list('ac'),columns=list("qwr"))
print(df_1)
print(df_2)
print(df_1*df_2)
#广播
print("array")
arr1 = np.array([np.arange(1,3),np.arange(3,5)])
# arr = np.array([1,3,4],[2,5,6])
# print(arr1+arr) #这里会报错 因为形状不一样 无法进行运算
arr2 = np.array([[1],[1]])
print(arr1)
print(arr2)
print(arr1+arr2)
print("DataFrame")
df = pd.DataFrame(np.arange(12).reshape(4,3),columns=list('abc'))
se = df['b']
print(df)
print(se)
print(df.sub(se,axis = 0))
print("排序:")
print("对索引进行排序:")
df = pd.DataFrame(np.arange(12).reshape(4,3),columns=list('abc'),index=['one','two','three','four'])
print(df)
print(df.sort_index()) #行索引排序
df = pd.DataFrame(np.arange(12).reshape(4,3),columns=list('acb'),index=['one','two','three','four'])
print(df)
print(df.sort_index(axis=1)) #列索引排序
print(df.sort_values(by=['a'])) #by是根据哪一列数值进行排序
print(df.sort_values(by=['a','b'])) #优先排a列 如果a列数值一样再看b列数值
print(df.sort_values(by=['a'],ascending=False)) #ascending为降序排列,
这些例子都有注释,也比较简单,基本对比运行结果一看就明白。