替换操作
-
替换操作可以同步作用于Series和DataFrame中
-
单值替换: 替换所有符合要求的元素 : to_replace=15 ,value="e"
-
按列指定单值替换: to_replace={列标签:替换值} value="xxx"
-
多值替换
列表替换 : to_replace=[] value=[]
字典替换(推荐) to_replace={to_replace:value,to_replace:value}
from pandas import Series, DataFrame
import pandas as pd
np.random.seed(0)
ret = pd.DataFrame(data=np.random.randint(0, 10, size=(4, 6)))
0 1 2 3 4 5
0 5 0 3 3 7 9
1 3 5 2 4 7 6
2 8 8 1 6 7 7
3 8 1 5 9 8 9
ret.replace(to_replace=7, value="er" , inplace=True) # 单个替换 替换所有
0 1 2 3 4 5
0 5 0 3 3 er 9
1 3 5 2 4 er 6
2 8 8 1 6 er er
3 8 1 5 9 8 9
ret.replace(to_replace={7: "er", 3: "san"}, inplace=True) # 多值替换 替换所有
0 1 2 3 4 5
0 5 0 san san er 9
1 san 5 2 4 er 6
2 8 8 1 6 er er
3 8 1 5 9 8 9
ret.replace(to_replace={0: 5}, value="five", inplace=True) # 指定列 替换 第 0 列 的5 替换成 five
0 1 2 3 4 5
0 five 0 3 3 7 9
1 3 5 2 4 7 6
2 8 8 1 6 7 7
3 8 1 5 9 8 9
映射操作
- 概念:创建一个映射关系表,把values元素和一个特定的标签或则字符串绑定(给一个元素提供不同的表现形式)
- 创建一个df,两列分别是姓名和薪资,然后给起名字起对应的英文名
# 映射
dic = {
"name": ["王镇", "田胖", "胖"],
"salary": [1000, 2000, 3000]
}
dic1 = {
"王镇": "wz",
"田胖": "tp",
"胖": "p"
} # 映射关系表 指定好了一一映射的关系
df = DataFrame(data=dic)
name salary
0 王镇 1000
1 田胖 2000
2 胖 3000
ret = df["name"].map(dic1) # map 是属于 Series的方法 只能series调用
0 wz
1 tp
2 p
df["e_name"]=ret
name salary e_name
0 王镇 1000 wz
1 田胖 2000 tp
2 胖 3000 p
map 运算工具
- 超过3000部分的钱缴纳50%的税。计算每个人的税后薪资
dic = {
"name": ["王镇", "田胖", "胖"],
"salary": [10000, 20000, 30000]
}
def after_sal(s):
return s-(s-3000)*0.5
df = DataFrame(data=dic)
ret = df["salary"].map(after_sal)
df["after_sal"] = ret
name salary after_sal
0 王镇 10000 6500.0
1 田胖 20000 11500.0
2 胖 30000 16500.0
####### 排序实现的随机抽样 将数据打乱 指将行列索引打乱
df = DataFrame(data=np.random.randint(0, 100, size=(10, 3)), columns=["a", "b", "c"])
a b c
0 19 37 33
1 26 41 17
2 72 39 89
3 50 38 9
4 64 97 96
5 53 55 97
6 62 57 29
7 80 75 81
8 45 40 2
9 74 70 14
index = np.random.permutation(3) # 随机生成乱序列表
[2 0 1]
rrr= df.take(indices=index, axis=1) # 只能用隐式的列索引 不能用显示的 【"b","a","c"】不行 打乱列
c a b
0 33 19 37
1 17 26 41
2 89 72 39
3 9 50 38
4 96 64 97
5 97 53 55
6 29 62 57
7 81 80 75
8 2 45 40
9 14 74 70
df.take(indices=np.random.permutation(10), axis=0) # 打乱行
a b c
0 96 11 40
2 10 42 13
6 40 84 85
1 91 0 16
7 56 65 75
9 79 10 25
5 14 22 38
4 58 66 60
3 56 5 41
8 24 16 53
数据的分类处理
- 数据的处理的核心:
groupby()函数
groups 属性查看分组情况
df = DataFrame(data={"item": ["Apple", "Banana", "Orange", "Banana", "Orange", "Apple"],
"price": [4, 3, 3, 2.5, 4, 2],
"color": ["red", "yellow", "yellow", "green", "green", "green"],
"weight": [12, 20, 50, 30, 20, 44]
})
item price color weight
0 Apple 4.0 red 12
1 Banana 3.0 yellow 20
2 Orange 3.0 yellow 50
3 Banana 2.5 green 30
4 Orange 4.0 green 20
5 Apple 2.0 green 44
ret = df.groupby(by="item") # 按种类分组
ret.groups # 查看分组情况
{'Apple': Int64Index([0, 5], dtype='int64'), 'Banana': Int64Index([1, 3], dtype='int64'), 'Orange': Int64Index([2, 4], dtype='int64')}
# 计算每种水果的平均价格
mean_df = df.groupby(by="item").mean()
price weight
item
Apple 3.00 28
Banana 2.75 25
Orange 3.50 35
mean_price = df.groupby(by="item").mean()["price"] # 不推荐 因为会多算了一个重量均值
item
Apple 3.00
Banana 2.75
Orange 3.50
Name: price, dtype: float64
mean_price1 = df.groupby(by="item")["price"].mean() # 推荐写法
item
Apple 3.00
Banana 2.75
Orange 3.50
Name: price, dtype: float64
# 把 平均价格 添加回原表
mean_price.to_dict() # 转成字典形式
{'Apple': 3.0, 'Banana': 2.75, 'Orange': 3.5}
df["mean_price"] = df["item"].map(mean_price.to_dict()) # 映射
item price color weight mean_price
0 Apple 4.0 red 12 3.00
1 Banana 3.0 yellow 20 2.75
2 Orange 3.0 yellow 50 3.50
3 Banana 2.5 green 30 2.75
4 Orange 4.0 green 20 3.50
5 Apple 2.0 green 44 3.00
# 求出每种颜色水果的平均重量 并汇总回原数据
df.groupby(by="color")["weight"].mean()
color
green 31.333333
red 12.000000
yellow 35.000000
Name: weight, dtype: float64
df["mean_weight"] = df["color"].map(ret.to_dict())
df
item price color weight mean_weight
0 Apple 4.0 red 12 12.000000
1 Banana 3.0 yellow 20 35.000000
2 Orange 3.0 yellow 50 35.000000
3 Banana 2.5 green 30 31.333333
4 Orange 4.0 green 20 31.333333
5 Apple 2.0 green 44 31.333333
高级数据聚合
-
使用groupby分组后,也可以使用transform 和 apply 提供自定义函数实现更多的运算
-
df.groupby("item")["price"].sum()<==>df.groupby("item")["price"].apply(sum)
-
transform 和 apply 都会进行运算,在transform或者apply中传入函数即可
-
transform 和 apply 也可以传入一个lambda表达式
-
apply 和 transform返回结果的区别?
transform是对返回结果进行了映射操作,而apply没有
# 分组后使用我们自定义的聚合函数实现分组聚合
def my_mean(s):
sum = 0
for i in s:
sum += i
return sum / len(s)
df.groupby(by="color")["weight"].apply(my_mean)
color
green 31.333333
red 12.000000
yellow 35.000000
Name: weight, dtype: float64
df.groupby(by="color")["weight"].transform(my_mean)
0 12.000000
1 35.000000
2 35.000000
3 31.333333
4 31.333333
5 31.333333
Name: weight, dtype: float64
数据加载
- 读取type-txt文件
pd.read_csv("./1234.txt")
你好-我好-大家好
0 也许-大概-有可能
1 然而-未必-不见得
pd.read_csv("./1234.txt",sep="-") # 默认分隔是","
你好 我好 大家好
0 也许 大概 有可能
1 然而 未必 不见得
pd.read_csv("./1234.txt",sep="-",header=None) # 不把第一条数据当标题
0 1 2
0 你好 我好 大家好
1 也许 大概 有可能
2 然而 未必 不见得
读取数据库中的数据
import sqlite3 as sql
conn = sql.connect("xxxxxx") # 可以是各种数据库
sql_df = pd.read_sql("select * from table",conn)
# 将一个df中的数据存到db中
sql_df.to_sql("table_name",conn) # table_name 表名 mysql的库不能用这种方法
透视表
- 透视表是一种可以对数据动态排布并且分类汇总的表格格式。或许大多数人在Excel使用过透视表,也体会过它的强大功能,而在pandas中它被称作pivot_table。
- 透视表的优点
-- 灵活性高,可以随意定制你的分析计算要求
-- 脉络清晰易于理解数据
-- 操作性强,报表神器
视频链接 没有数据表 自己写太麻烦了 直接上视频
网友评论