pandas 简单使用

pandas的简单使用记录

创建

  • 由数据库查询创建

  • 自定义数据创建

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    lst=[[1,2,'apple'],[3,4,'banan']]
    frm=pd.DataFrame(lst, columns=['tag1','tag2', 'tag3'])

    # 创建子集 , 可指定行区间\列名
    frm2=frm.loc[:,['tag1', 'tag3']]


    # 从表中读取
    query = Model.query.session.query(Model.local_date, Model.data_source, func.sum(Model.total).label('t'), func.sum(Model.count).label('c'))
    with AlchemyDbUtil(db, 'statistics') as dbutil:
    pdf=pd.read_sql(query.statement, dbutil.conn)

查看

* head, tail, describle()


* 排序
    
1
frame.sort_index(by=['column1'],ascending=False)
* 过滤
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 清除null
frm3=frm2.dropna(subset=['tag2'])

# 一行数据只要有一个字段存在空值即删除
frm2.dropna(axis=0, how="any")
#how 参数可选的值为 any(默认) 或者 all。any 表示一行/列有任意元素为空时即丢弃,all 一行/列所有值都为空时才丢弃。
#subset 参数表示删除时只考虑的索引或列名。
#thresh参数的类型为整数,它的作用是,比如 thresh=3,会在一行/列中至少有 3 个非空值时将其保留。


# 过滤空串
frm3=frm3[frm3['tag2']!='']

# 按条件过滤
frm3=frm3[frm3['tag2']!=frm3['tag1']]

# 取toplist
frm_main.nlargest(10, 'cnt')

# 分组后取toplist nlargest()的第一个参数就是截取的行数。第二个参数就是依据的列名
frm_main.groupby(by=['airline_code', 'iata_code']).apply(lambda x: x.nlargest(1,"cnt"))


* 遍历 |tag1| tag2| cnt| |---|---|---| |6H |C3|6| |8Q |SV|4|
1
2
for idx , item  in frm4.iterrows():
print idx, '--', item[0], item[1], item[2]
* 导出 to_csv, clipboard ... ![示例](http://ww3.sinaimg.cn/large/006tNc79ly1g60imisu3qj305205vglt.jpg) * 统计
1
2
3
4
5

# 相当于groupby tag1, tag2 having count(1) >2
frm4=frm3.groupby(['tag1', 'tag2']).size().reset_index(name='cnt').query('cnt >2')


修改

* 动态生成\修改列
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 由其它列生成
frm['tag_short']=frm['tag3'].str[:2]

# 由其它函数生成
reg_dict={
...
}
for idx in frm.index:
frm.loc[idx]['tag_new']=reg_dict.get(frm.loc[idx]['key'], '')

# 由lambda表达式生成
def apply_func(df):
return reg_dict.get(df['key'], '')

frm['tag_new']=frm.apply(lambda r:apply_apairline(r), axis=1)

* 清除空数据
1
2
# # 可以通过subset参数来删除在age和sex中含有空数据的全部行
df4 = df4.dropna(subset=["age", "sex"])