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"])

json 格式化 datetime, date

json.dumps() 对datetime.datetime, datetime.date类型数据无法识别会报错, 需要自定义encoder 来解决
在学习flask的源码中,了解了偏函数 ,可以创建原函数的代理,支持预设参数,还可保留原来该用方式

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

from functools import partial

class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, datetime.date):
return obj.strftime("%Y-%m-%d")
else:
return json.JSONEncoder.default(self, obj)


json_dump=partial(json.dumps, ensure_ascii=False, cls=DateEncoder)


调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

import copy

class User(object):

def __init__(self, id, sname):
self.id=id
self.sname=sname
self.time=datetime.datetime.now()
self.sname_zh='汉字'


def __repr__(self):
self_dict = copy.deepcopy(self.__dict__)
return json_dump(self_dict, indent=2 )


print User(1, 'admin')

>>> {
"time": "2019-08-13 14:04:21",
"sname": "admin",
"id": 1,
"sname_zh": "汉字"
}

数据导出\导入

mysqldump

  • -t 只导出数据 ,不导结构 , --skip-lock-tables 不锁表

    mysqldump -h127.0.0.1 -P3306 -uuser -ppwd -t --skip-lock-tables test tab1>tab1.sql

  • -d 只备份结构 --skip-add-drop-table 禁用drop tabe(默认会有drop table)

    mysqldump -hlocalhost -P3306 -uuser -ppwd -d --skip-add-drop-table test tab1> test.tab1.sql

  • 整库备份

    mysqldump -hlocalhost -P3306 -uuser -ppwd -B test > test.sql

  • 重要参数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    -B:指定多个库,在备份文件中增加建库语句和use语句
    --compact:去掉备份文件中的注释,适合调试,生产场景不用
    -A:备份所有库
    -F:刷新binlog日志
    --master-data:在备份文件中增加binlog日志文件名及对应的位置点
    -x --lock-all-tables:锁表
    -l:只读锁表
    -d:只备份表结构
    -t:只备份数据
    --single-transaction:适合innodb事务数据库的备份
    InnoDB表在备份时,通常启用选项--single-transaction来保证备份的一致性,原理是设定本次会话的隔离级别为Repeatable read,来保证本次会话(也就是dump)时,不会看到其它会话已经提交了的数据。

    导入备份数据

  • 命令行导入

    mysql -hlocalhost -P3306 -uuser -ppwd test < test.test.sql

查询

  • 命令行查询

    mysql -hlocalhost -P3306 -uroot -p123456 -e "use test; set names utf8; select * from img_library limit 10;" > tmp.xls

go test -v

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1
$ hexo new "My New Post"

More info: Writing

Run server

1
$ hexo server

More info: Server


Generate static files

1
$ hexo generate

More info: Generating

Deploy to remote sites

1
$ hexo deploy

More info: Deployment