大数跨境

Pandas 数据分析 5 个实用小技巧

Pandas 数据分析 5 个实用小技巧 Python程序员
2020-11-30
0
导读:留言送3本机器学习实战:基于Scikit-Learn、Keras和TensorFlow(原书第2版)


小技巧1:如何使用map对某些列做特征工程?

先生成数据:

d = {
"gender":["male", "female", "male","female"],
"color":["red", "green", "blue","green"],
"age":[25, 30, 15, 32]
}

df = pd.DataFrame(d)
df

在 gender 列上,使用 map 方法,快速完成如下映射:

d = {"male": 0, "female": 1}
df["gender2"] = df["gender"].map(d)

小技巧2:使用 replace 和正则清洗数据

Pandas 的强项在于数据分析,自然就少不了数据清洗。

一个快速清洗数据的小技巧,在某列上使用 replace 方法和正则,快速完成值的清洗。

源数据:

d = {"customer": ["A", "B", "C", "D"],
"sales":[1100, "950.5RMB", "$400", " $1250.75"]}

df = pd.DataFrame(d)
df

打印结果:

customer sales
0 A 1100
1 B 950.5RMB
2 C $400
3 D $1250.75

看到 sales 列的值,有整型,浮点型+RMB后变为字符串型,还有美元+整型,美元+浮点型。

我们的目标:清洗掉 RMB,$ 符号,转化这一列为浮点型。

一行代码搞定:(点击代码区域,向右滑动,查看完整代码)

df["sales"] = df["sales"].replace("[$,RMB]",
                                  "", regex = True) \
.astype("float")

使用正则替换,将要替换的字符放到列表中 [$,RMB],替换为空字符,即 "";

最后使用 astype 转为 float

打印结果:

customer sales
0 A 1100.00
1 B 950.50
2 C 400.00
3 D 1250.75

如果不放心,再检查下值的类型:

df["sales"].apply(type)

打印结果:

0    <class 'float'>
1    <class 'float'>
2    <class 'float'>
3    <class 'float'>

小技巧3:使用 melt 如何对数据透视分析?

构造一个 DataFrame:

d = {\
"district_code": [12345, 56789, 101112, 131415],
"apple": [5.2, 2.4, 4.2, 3.6],
"banana": [3.5, 1.9, 4.0, 2.3],
"orange": [8.0, 7.5, 6.4, 3.9]
}
  
df = pd.DataFrame(d)
df

打印结果:

district_code apple banana orange
0123455.23.58.0
1567892.41.97.5
21011124.24.06.4
31314153.62.33.9

5.2 表示 12345 区域的 apple 价格,并且 apple, banana, orange,这三列都是一种水果,那么如何把这三列合并为一列?

使用 pd.melt

具体参数取值,根据此例去推敲:

df = df.melt(\
id_vars = "district_code",
var_name = "fruit_name",
value_name = "price")
df

打印结果:

district_code fruit_name price
012345 apple 5.2
156789 apple 2.4
2101112 apple 4.2
3131415 apple 3.6
412345 banana 3.5
556789 banana 1.9
6101112 banana 4.0
7131415 banana 2.3
812345 orange 8.0
956789 orange 7.5
10101112 orange 6.4
11131415 orange 3.9

以上就是长 DataFrame,对应的原 DataFrame 是宽 DF.

小技巧4:已知 year 和 dayofyear,怎么转 datetime?

原 DataFrame

d = {\
"year": [2019, 2019, 2020],
"day_of_year": [350, 365, 1]
}
df = pd.DataFrame(d)
df

打印结果:

  year day_of_year
02019350
12019365
220201

转 datetime 的 小技巧

步骤 1: 创建整数

df["int_number"] =
df["year"]*1000 + df["day_of_year"]

打印 df 结果:

year day_of_year int_number
020193502019350
120193652019365
2202012020001

步骤 2: to_datetime

df["date"]=pd.to_datetime(df["int_number"],
format = "%Y%j")

注意 "%Y%j" 中转化格式 j

打印结果:

 year day_of_year int_number date
0201935020193502019-12-16
1201936520193652019-12-31
22020120200012020-01-01

小技巧5:如何将分类中出现次数较少的值归为 others?

这也是我们在数据清洗、特征构造中面临的一个任务。

如下一个 DataFrame:

d = {"name":['Jone','Alica','Emily','Robert','Tomas',
             'Zhang','Liu','Wang','Jack','Wsx','Guo'],
     "categories": ["A", "C", "A", "D", "A", 
                    "B", "B", "C", "A", "E", "F"]}
df = pd.DataFrame(d)
df

结果:

 name categories
0 Jone A
1 Alica C
2 Emily A
3 Robert D
4 Tomas A
5 Zhang B
6 Liu B
7 Wang C
8 Jack A
9 Wsx E
10 Guo F

D、E、F 仅在分类中出现一次,A 出现次数较多。

步骤 1:统计频次,并归一

frequencies = df["categories"].value_counts(normalize = True)
frequencies

结果:

A    0.363636
B    0.181818
C    0.181818
F    0.090909
E    0.090909
D    0.090909
Name: categories, dtype: float64

步骤 2:设定阈值,过滤出频次较少的值

threshold = 0.1
small_categories = frequencies[frequencies < threshold].index
small_categories

结果:

Index(['F', 'E', 'D'], dtype='object')

步骤 3:替换值

df["categories"] = df["categories"] \
.replace(small_categories, "Others")

替换后的 DataFrame:

 name categories
0 Jone A
1 Alica C
2 Emily A
3 Robert Others
4 Tomas A
5 Zhang B
6 Liu B
7 Wang C
8 Jack A
9 Wsx Others
10 Guo Others




今天给大家推荐一本机器学习、深度学习的人都应该听说过一本经典教材: 《Pattern Recognition and Machine Learning》,中文译名《模式识别与机器学习》,简称 PRML。 出自微软剑桥研究院实验室主任 Christopher Bishop 大神之手。 对,就是豆瓣评分 9.5 的这本书。



资料获取方法

1. 扫描下方二维码
2. 后台回复关键词: PRML

 
 
 
 
👆长按上方二维码 2 秒
回复「PRML」即可获取资料
【声明】内容源于网络
0
0
Python程序员
1234
内容 2525
粉丝 0
Python程序员 1234
总阅读0
粉丝0
内容2.5k