pandas groupby函数
pandas的groupby函数一般会配合合计函数使用,比如,count、avg等等。
首先讲解几种模式,然后示例上场:
第一种:df.groupby(col),返回一个按列进行分组的groupby对象;
第二种:df.groupby([col1,col2]),返回一个按多列进行分组的groupby对象;
第三种:df.groupby(col1)[col2]或者df[col2].groupby(col1),两者含义相同,返回按列col1进行分组后,col2的值;
先创建一个DataFrame对象df:
创建一个DataFrame对象df 结果数据import pandasas pd
from dateutil.parserimport parse
import datetimeas dt
import matplotlib.pyplotas plt
df= pd.DataFrame({'Date': ['2015-05-08','2015-05-07','2015-05-06','2015-05-05','2015-05-08','2015-05-07','2015-05-06','2015-05-05'],
'Sym': ['aapl','aapl','aapl','aapl','aaww','aaww','aaww','aaww'],
'Data2': [11,8,10,15,110,60,100,40],
'Data3': [5,8,6,1,50,100,60,120]})
第一种:df.groupby(col),返回一个按列进行分组的groupby对象;
对日期进行分组,打印出结果样式,结果如下:
df.groupby(col)import pandasas pd
from dateutil.parserimport parse
import datetimeas dt
import matplotlib.pyplotas plt
df= pd.DataFrame({'Date': ['2015-05-08','2015-05-07','2015-05-06','2015-05-05','2015-05-08','2015-05-07','2015-05-06','2015-05-05'],
'Sym': ['aapl','aapl','aapl','aapl','aapl','aapl','aaww','aaww'],
'Data2': [11,8,10,15,110,60,100,40],
'Data3': [5,8,6,1,50,100,60,120]})
df1=df.groupby(df['Date'])
print(list(df1))
第二种:df.groupby([col1,col2]),返回一个按多列进行分组的groupby对象;
df.groupby([col1,col2])代码 df.groupby([col1,col2])结果import pandasas pd
from dateutil.parserimport parse
import datetimeas dt
import matplotlib.pyplotas plt
df= pd.DataFrame({'Date': ['2015-05-08','2015-05-07','2015-05-06','2015-05-05','2015-05-08','2015-05-07','2015-05-06','2015-05-05'],
'Sym': ['aapl','aapl','aapl','aapl','aapl','aapl','aaww','aaww'],
'Data2': [11,8,10,15,110,60,100,40],
'Data3': [5,8,6,1,50,100,60,120]})
df1=df.groupby(['Date','Sym'])
print(list(df1))
第三种:df.groupby(col1)[col2]或者df[col2].groupby(col1),两者含义相同,返回按列col1进行分组后,col2的值;
import pandasas pd
from dateutil.parserimport parse
import datetimeas dt
import matplotlib.pyplotas plt
df= pd.DataFrame({'Date': ['2015-05-08','2015-05-07','2015-05-06','2015-05-05','2015-05-08','2015-05-07','2015-05-06','2015-05-05'],
'Sym': ['aapl','aapl','aapl','aapl','aapl','aapl','aaww','aaww'],
'Data2': [11,8,10,15,110,60,100,40],
'Data3': [5,8,6,1,50,100,60,120]})
df1=df.groupby(df['Date'])['Sym']
print(list(df1))
df.groupby(col1)[col2]
df.groupby(col1)[col2]
df['Sym'].groupby(df['Date']) df['Sym'].groupby(df['Date'])import pandasas pd
from dateutil.parserimport parse
import datetimeas dt
import matplotlib.pyplotas plt
df= pd.DataFrame({'Date': ['2015-05-08','2015-05-07','2015-05-06','2015-05-05','2015-05-08','2015-05-07','2015-05-06','2015-05-05'],
'Sym': ['aapl','aapl','aapl','aapl','aapl','aapl','aaww','aaww'],
'Data2': [11,8,10,15,110,60,100,40],
'Data3': [5,8,6,1,50,100,60,120]})
df1=df['Sym'].groupby(df['Date'])
print(list(df1))
好啦,就到这啦,谢谢
网友评论