import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
s= pd.Series([1,2,3,np.nan,5,6,]) #series 类型数组。
s
dates= pd.date_range("20170112",periods=6) #Creating a DataFrame by passing a numpy array, with a datetime index and labeled column
dates
list(dates)
dates.date
list(dates.date)
dates.year
list(dates.year)
list(dates.day)
str(dates.date)
df=pd.DataFrame(np.random.randn(6,4),index=dates,columns=list("ABCD"))
df
df2 = pd.DataFrame({ 'A' : 1.,
'B' : pd.Timestamp('20130102'),
'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
'D' : np.array([3] * 4,dtype='int32'),
'E' : pd.Categorical(["test","train","test","train"]),
'F' : 'foo' }) #Creating a DataFrame by passing a dict of objects that can be converted to series-like.
df2
df2.dtypes
df.dtypes
df2.<TAB> #使用jupyter时按tab键,可以看到代码提示。
df.head()
df.index
df.columns
df.values
df.describe()
df
df.T
df.sort_index(axis=1,ascending=False) #Sorting by an axis 排序。
df.sort_values(by="B") #Sorting by values
df
df["A"]# Selecting a single column, which yields a Series, equivalent to df.A
df.A
df[0:3] #Selecting via [], which slices the rows.
df["2017-01-13":"2017-01-17"]
dates
df.loc[dates[0]] #For getting a cross section using a label
df.loc[:,["A","B"]]
df.loc['20170112':'20170116',['A','B']] #Showing label slicing, both endpoints are included
df.loc["20170115",["A","B"]]
df.loc[dates[3],"D"] #For getting a scalar value
df.at[dates[3],"D"] #For getting fast access to a scalar (equiv to the prior method)
df.iloc[3] #Select via the position of the passed integers
df.iloc[2:5,0:2] # By integer slices, acting similar to numpy/python
df.iloc[[1,3,4],[0,2]] #By lists of integer position locations, similar to the numpy/python style
df.iloc[1:3,:]
df.iloc[:,1:3]
df.iloc[1,1] #For getting a value explicitly
df.iat[1,1] #For getting fast access to a scalar (equiv to the prior method)
df[df.A>0] #Using a single column’s values to select data
df[df>0] #Selecting values from a DataFrame where a boolean condition is met
df2
df
df2=df.copy()
df2
df.equals(df2)
df==df2
df is df2
df2["E"]=["one","one","two","three","four","three"]
df2
df2[df2.E.isin(["two","four"])]
df2[df2["E"].isin(["two","four"])]
s1= pd.Series([1,2,3,4,5,6],index=pd.date_range("20171016",periods=6)) #Setting a new column automatically aligns the data by the indexes
s1
df.at[dates[0],"A"]=0 #Setting values by label
df
df.iat[0,1]=0
df
df.loc[:,"D"]=np.array([5]*len(df)) #Setting by assigning with a numpy array
df
df2=df.copy()
df2
df2[df2>0]=-df2
df2
df
df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + ['E'])
df1.loc[dates[0]:dates[1],'E'] = 1
df1
df1.dropna(how="any") #To drop any rows that have missing data
df1.fillna(value=5) # Filling missing data
df1
pd.isnull(df1)
df1.isnull()
df1.isna() #没有这个方法~~
df
df.mean()
df.mean(1) #Same operation on the other axis
s= pd.Series([1,2,3,np.nan,4,5],index=dates).shift(2)
# Operating with objects that have different dimensionality and need alignment. In addition, pandas automatically broadcasts along the specified dimension.
s
df
df.sub(s,axis="index") #dataFrame与series的减法
df
df.apply(np.cumsum) #行叠加。
df.apply(lambda x: x.max()-x.min())
s= pd.Series(np.random.randint(0,7,size=10))
s
s.value_counts()
s= pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
s.str.lower()
s
df
df=pd.DataFrame(np.random.randn(10,4))
df
# break it into pieces
pieces=[df[:3],df[3:7],df[7:]]
pd.concat(pieces)
pieces
left=pd.DataFrame({"key":["foo","foo"],"lval":[1,2]})
right = pd.DataFrame({'key': ['foo', 'foo'], 'rval': [4, 5]})
left
right
pd.merge(left,right,on="key")
left = pd.DataFrame({'key': ['foo', 'bar'], 'lval': [1, 2]})
right = pd.DataFrame({'key': ['foo', 'bar'], 'rval': [4, 5]})
left
right
pd.merge(left,right,on="key")
df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
df
s=df.iloc[3]
s
df.append(s,ignore_index=True)
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C' : np.random.randn(8),
'D' : np.random.randn(8)})
df
df.groupby("A").sum()
df.groupby(["A","B"]).sum() #Grouping by multiple columns forms a hierarchical index, which we then apply the function.
tuples = list(zip([['bar', 'bar', 'baz', 'baz',
'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two',
'one', 'two', 'one', 'two']]))
tuples
tuples = list(zip(*[['bar', 'bar', 'baz', 'baz',
'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two',
'one', 'two', 'one', 'two']]))
tuples
index=pd.MultiIndex.from_tuples(tuples,names=["first","second"])
index
df=pd.DataFrame(np.random.randn(8,2),index=index,columns=['A', 'B'])
df
df2=df[:4]
df2
stacked= df2.stack()
stacked
stacked.unstack()
stacked.unstack(1)
stacked.unstack(0)
df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three'] * 3,
'B' : ['A', 'B', 'C'] * 4,
'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 2,
'D' : np.random.randn(12),
'E' : np.random.randn(12)})
df
pd.pivot_table(df,values="D",index=["A","B"],columns=["C"])
rng=pd.date_range("1/2/2017",periods=100,freq="S")
rng
ts =pd.Series(np.random.randint(0,500,len(rng)),index=rng)
ts
ts.resample("5Min").sum()
ts.resample("1Min").sum()
rng= pd.date_range("2/1/2017 00:00",periods=5,freq="D")
rng
ts=pd.Series(np.random.randn(len(rng)),index=rng)
ts
tsUtc=ts.tz_localize("UTC")
tsUtc
tsUtc.tz_convert("US/Eastern")
tsUtc
rng=pd.date_range("1/8/2017",periods=5,freq="M")
rng
ts=pd.Series(np.random.randn(len(rng)),rng)
ts
ps=ts.to_period()
ps
ps.to_timestamp()
ps
prng=pd.period_range("1990Q1","2017Q4",freq="Q-NOV")
prng
ts= pd.Series(np.random.randn(len(prng)),prng)
ts.head()
ts.index=(prng.asfreq("M","e")+1).asfreq("H","s")+9
ts.head()
df = pd.DataFrame({"id":[1,2,3,4,5,6],"raw_grade":["a","a","c","b","b","f"]})
df
df["grade"]=df.raw_grade.astype("category")
df
df.grade #Convert the raw grades to a categorical data type
# Rename the categories to more meaningful names (assigning to Series.cat.categories is inplace!)
df.grade.cat.categories=["very good","good","nomal","bad"]
df
# Reorder the categories and simultaneously add the missing categories (methods under Series .cat return a new Series per default).
df.grade=df.grade.cat.set_categories(["very bad", "bad", "medium","good", "very good"])
df.grade
df
df.sort_values(by="grade")
df.groupby("grade").size()
ts=pd.Series(np.random.randn(1000),index=pd.date_range("1/1/2017",periods=1000))
ts.head()
ts=ts.cumsum()
ts.head()
ts.plot()
df=pd.DataFrame(np.random.randn(1000,4),index=ts.index,columns=["A","B","C","D"])
df.head()
df=df.cumsum()
plt.figure()
df.plot()
plt.legend(loc="best")
plt.show()
df.to_csv("foo.csv")
pd.read_csv("foo.csv")
df.to_hdf("foo.h5","df")
pd.read_hdf("foo.h5","df")
df.to_excel('foo.xlsx', sheet_name='Sheet1')
pd.read_excel('foo.xlsx', 'Sheet1', index_col=None, na_values=['NA'])