博客地址:http://www.cnblogs.com/yudanqu/
1 import numpy as np
import pandas as pd
from pandas import Series,DataFrame
#Series
s1 = Series([1,2,3], index=['A','B','C'])
s2 = Series([4,5,6,7], index=['B','C','D','E'])
s1 + s2
# 结果:A NaN
# B 6.0
# C 8.0
# D NaN
# E NaN
# dtype: float64
# 对应项相加,其他为nan
#DataFrame
df1 = DataFrame(np.arange(4).reshape(2,2),index=['A','B'],columns=['BJ','SH'])
df2 = DataFrame(np.arange(9).reshape(3,3),index=['A','B','C'],columns=['BJ','SH','GZ'])
df1 + df2
#结果: BJ GZ SH
# A 0.0 NaN 2.0
# B 5.0 NaN 7.0
# C NaN NaN NaN
df3 = Datadf3 = DataFrame([[1,2,3],[4,5,np.nan],[7,8,9]],index=['A','B','C'],columns=['c1','c2','c3'])
'''
c1 c2 c3
A 1 2 3.0
B 4 5 NaN
C 7 8 9.0
'''
df3.sum()
#结果:c1 12.0
# c2 15.0
# c3 12.0
# dtype: float64
#这里的nan与实数相运算并不返回nan
df3.sum(axis=1) #则求得每一行的和,即ABC,由于默认axis=0,所以不写表示求的列
df3.min() #求最小值,max同理。整体同理与sum,不考虑nan
df3.describe() #统计内部数据
# 排序功能
#注:randn:正态分布
rand:0到1
#Series:
s1 = Series(np.random.randn(10))
s2 = s1.sort_values() # 根据values排序
# 默认参数ascending=True,升序为True,倒序可以改参数sacending=False
s2.sort_index() # 根据index升序排列
#DataFrame:
df1 = DataFrame(np.random.randn(40).reshape(8,5),columns=['A','B','C','D','E'])
df1['A'].sort_values() #仅仅是对着一列排序,若想整体根据这一列进行排序要多df1进行排序
df1.sort_values('A') #则为全部排序,默认升序
df1.sort_values('A')[['A','D']] # 根据某列排序并输出所需要的几列
#重命名
df1.index = df1.index.map(str) #修改dataframe的index
df1.rename(index=str.upper,columns=str.lower) #通过map函数改变整个
df1.rename(index={'A':'a'},columns={'B':'b'}) #通过字典修改某一项
# map函数的参数可以使自己定义的函数
#dataframe的merge操作
pd.merge(df1,df2,on='name',how='inner') # on表示根据哪列的name来作为判断依据,默认为None,how的参数中比如写left,那么就根据左侧的df;爱显示数据,若右边一个没有的则补全为nan,outer是right和left的结合,将所有的都输出
df1 = DataFrame({'key':['A','B','C'],'data_set_1':[1,2,3]})
df2 = DataFrame({'key':['X','Y','Z'],'data_set_2':[4,5,6]})
pd.merge(df1,df2) # 这时的结果返回为空,因为merge是对其中key值相同的进行操作
# 当相同name的columns(例如此例的key)时,他中的值相同,那么可以进行merge
#concatenate和combine
#~~concatenate:
#1、array
arr1 = np.arange(9).reshape(3,3)
arr2 = np.arange(9).reshape(3,3)
np.concatenate([arr1,arr2]) #通过列表放在一起
'''
output:array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
注:其中concatenate的参数包括axis,可以决定如何连接
'''
#2、Series
s1 = Series([1,2,3],index=['X','Y','Z'])
s2 = Series([4,5],index=['A','B'])
pd.concat([s1,s2]) #同样有axis参数,为0则在下面连接,为1则横向
#3、dataframe
df1 = DataFrame(np.random.randn(4,3),columns=['X','Y','Z'])
df2 = DataFrame(np.random.randn(3,3),columns=['X','Y','A'])
pd.concat([df1,df2])
'''
Out:
A X Y Z
0 NaN -0.060523 0.879124 1.673622
1 NaN 0.734367 0.708085 -0.133981
2 NaN 0.461922 -2.186110 -4.473558
3 NaN 1.553153 -2.256533 -0.381862
0 1.304371 -0.275638 1.362799 NaN
1 -0.357986 -0.273505 0.430566 NaN
2 1.406862 1.453295 -0.681261 NaN
'''
#~~combine:
#1、Series:
s1 = Series([2,np.nan,4,np.nan],index=['A','B','C','D'])
s1 = Series([1,2,3,4],index=['A','B','C','D'])
s1.combine_first(s2) #把s1中没有的填充上从s2
#2、DataFrame:
#和series几乎一样
作者:渔单渠
博客地址:http://www.cnblogs.com/yudanqu/