Fork me on GitHub

pandas技巧2

总结下pandas使用的技巧

读取json数据并转成Python格式

计数功能实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 方法1
def get_counts(sequence):
counts = {} # 将计数值保存在字典中
for x in sequence:
if x in counts:
counts[x] += 1 # 存在则计数加1
else:
counts[x] = 1 # 不存在则定为1
return counts


# 方法2
from collections import defaultdict

def get_counts2(sequence):
counts = defaultdict(int)
for x in sequence:
counts[x] += 1
return counts

缺失值填充

利用seaborn制作条形堆积图

如何标准化数据

1
2
3
4
# 标准化过程:使用自定义的标准化函数实现
def normal_total(group):
group['normed_total'] = group.total / group.total.sum()
return group

透视表制作

1
2
3
4
5
6
# 按照性别计算平均得分
mean_ratings = data.pivot_table('rating', # 得分
index='title', # 行索引index
columns='gender', # 列属性gender
aggfunc='mean') # 使用的函数:平均分
mean_ratings[:5]

查看文件的前n行

1
2
!head -n 10 /Users/peter/data-visualization/pydata-book/datasets/babynames/yob1880.txt
# 查看某个文件的前10行数据

生成DF数据时自定义列属性

多个文件同时合并

本文标题:pandas技巧2

发布时间:2020年01月02日 - 11:01

原始链接:http://www.renpeter.cn/2020/01/02/pandas%E6%8A%80%E5%B7%A72.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Coffee or Tea